在过去的vue项目中元素想要动态更改css属性,就必须在标签中使用自定义属性的方式绑定css属性,而当属性值变多时就会使模板代码非常臃肿不利于后期维护,特别使在编写自定义组件时,往往需要向组件传递大量的css属性,而vue3项目可以使用v-bind在css中绑定js里的数据,这就使动态绑定属性只要像正常写css一样的方便。
单文件组件的 <style>
标签支持使用 v-bind
CSS 函数将 CSS 的值链接到动态的组件状态:
<script setup>
import {ref} from 'vue';
const theme = ref('red');
const colors = ['blue', 'yellow', 'red', 'green'];
setInterval(() => {
theme.value = colors[Math.floor(Math.random() * 4)];
}, 1000);
</script>
<template>
<p>hello</p>
</template>
<style scoped>
/* Modify the code to bind the dynamic color */
p {
color: v-bind(theme);
}
</style>
这个语法同样也适用于 <script setup>
,且支持 JavaScript
表达式 (需要用引号包裹起来):
<script setup>
const theme = {
color: 'red'
}
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
color: v-bind('theme.color');
}
</style>
实际的值会被编译成哈希化的 CSS 自定义属性,因此 CSS 本身仍然是静态的。自定义属性会通过内联样式的方式应用到组件的根元素上,并且在源值变更的时候响应式地更新。