vue css类动态样式(以下HTML代码包含在一个id=app的div中)
使用对象作为属性,其中键是类名,值是true或false。
<div class="demo" @click="attachRed=!attachRed":class="{red:attachRed}"></div>
使用对象:也可以将样式对象作为计算属性来处理将{red:attachRed,blue:!attachRed}存入计算属性的一个函数中,并在绑定class属性时调用,效果一样。
<div class="demo" @click="attachRed=!attachRed":class="{red:attachRed,blue:!attachRed}"></div>
使用命名:存具体值而不是布尔值()可以使用数组添加多个css类(数组元素可以是对象eg: :class="[color,{red:attachRed}]")
<div class="demo" :class="color"></div>
<input type="text" v-model="color">
内联style设置动态属性:绑定style属性,样式用对象表示。也可以将{backgroundColor:color}写入计算属性的一个函数中,在绑定style属性的地方调用。
同样可以使用混合数组添加多个样式,eg: :style="[color,{height:width+‘px’}]")
<div class="demo" :style="{backgroundColor:color}"></div>
js中的代码:
new Vue({
el:"#app",
data:{
value:0,
result:"",
attachRed:false,
effects:"highlight",
colors:"blue",
width:100
},
computed:{
output:function(){
return this.value==37?"done":"not there yet";
},
mystyle:function(){
return this.value==37?"done":"not there yet";
}
},
watch:{
output:function(newvalue,oldvalue){
var m =this;
console.log(m.value);
// console.log(oldvalue);
if(newvalue=="done"){
console.log("ok");
setTimeout(function(){
m.value=0;
},5000);
}
}
},
});
css中的类样式:
.demo{
width: 100px;
height: 100px;
display: inline-block;
background-color: gray;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}