如何在vue3的css中使用data中的变量。
很简单用v-bind
一个简单的例子
<template>
<div>
<h1 class="h1" >我是{{ color }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
color: 'red',
}
}
}
}
</script>
<style scoped>
.h1 {
color: v-bind(color);
}
</style>
运行如下图所示:成功设置了文字的颜色。
这样就可以做一个文字颜色不断变化的demo
<template>
<div>
<h1 class="h1" @click="changeColor">我是{{ color }}</h1>
<button @click="changeColor">变色</button>
</div>
</template>
<script>
export default {
components: {
Child,
},
data() {
return {
color: 'red',
count: 1,
}
},
created () {
setInterval(()=>{
this.changeColor()
},500)
},
methods: {
changeColor() {
const arr = [
'red',
'blue',
'pink',
'black',
'hotpink',
'purple',
'lime',
'skyblue',
]
this.color = arr[this.count]
this.count++
if (this.count === 8) {
this.count = 0
}
},
},
}
</script>
<style scoped>
.h1 {
color: v-bind(color);
}
</style>
运行结果如下图:
是不是感觉要方便许多。