我的某些单文件组件需要从道具上获取悬停颜色。
我的解决方案是,我通过以下方式设置css变量(主要部分在Mounted(){...}中)
<template>
<div class="btnWrapper" ref="btnWrapper">...</div>
</template>
...
...
props() {
color1: {type: String, default: 'blue'},
},
mounted () {
this.$refs.btnWrapper.style.setProperty('--wrapHoverColor', this.color1)
}
...
...
<style scoped>
.btnWrapper {
--wrapHoverColor: pink;
}
.btnWrapper:hover {
background-color: var(--wrapHoverColor) !important;
}
</style>
此解决方案似乎很吸引人。但是使用伪元素可能没有更好的方法,而伪元素很难从js中控制。你们曾经从vue组件的props中获取伪元素的属性吗?
您有两种不同的方法来执行此操作。
[您已经知道,您可以从要从JS移植到CSS的对象中创建CSS变量,并将它们放到组件:style
钩子上的根元素created
attr上,然后在CSS代码中使用它们var(--x)
。
<template>
<button :style="style"> Button </button>
</template>
<script>
export default {
props: ['color', 'hovercolor'],
data() {
return {
style: {
'--color': this.color,
'--hovercolor': this.hovercolor,
},
};
}
}
</script>
<style scoped>
button {
background: var(--color);
}
button:hover {
background: var(--hovercolor);
}
</style>
vue-component-style是一个很小的(〜1kb gzip压缩)mixin,可以在内部进行此操作。当您激活该混合时,您可以将您的整个style
部分写在具有对组件上下文的完全访问权限的组件对象内部。
<template>
<button class="$style.button"> Button </button>
</template>
<script>
export default {
props: ['color', 'hovercolor'],
style({ className }) {
return [
className('button', {
background: this.color,
'&:hover': {
background: this.hovercolor,
},
});
];
}
}
</script>