vue2的,动态样式只能通过computed实现
<view :style="colors">
<view class="text">
test css
</view>
</view>
//js
data(){
return {
color:'#84a555'
}
},
computed:{
colors () {
setInterval((res)=>{
this.color = `#${Math.random().toString(16).slice(-6)}`
console.log(this.color)
},500)
return "--color:" + this.color;
}
},
//css
.text{
color:var(--color);
}
vue3的可以通过在style的vars上实现
<h1>test css</h1>
data(){
return {
opacity:0,
}
},
mounted() {
setInterval(()=>{
this.opacity>=1 && (this.opacity=0)
this.opacity+=0.2
},300)
},
<style vars='{opacity}'>
h1{
color: rgb(65,184,131);
opacity: var(--opacity);
}
</style>
总结:
无论在 Vue3 还是 2 中,建议都使用计算属性的写法。