class的绑定
使用v-bind
进行class
的绑定
<div id="test1">
<div v-bind:class="{div_blue:isActive,'div_red':hasError}"></div>
</div>
.div_blue{
width: 200px;
height: 100px;
background: blue;
}
.div_red{
background: red;
}
var test1=new Vue({
el:'#test1',
data:{
isActive:true,
hasError:true
},
});
当data内属性变化,div所绑定的类的状态也会实时发生更新
也可以直接绑定data
中的一个对象:
<div id="test1">
<div v-bind:class="classObj"></div>
</div>
var test1=new Vue({
el:'#test1',
data:{
isActive:true,
hasError:true,
classObj:{
div_blue:true,
'div_red':true
}
},
});
这两种方法是等效的
最常用的方式是绑定一个返回对象的计算属性:
<div id="test1">
<div v-bind:class="classObj">测试文字</div>
</div>
.div_blue{
width: 200px;
height: 100px;
background: blue;
color: red;
}
.div_red{
background: red;
color: blue;
}
.size{
width: 100px;
height: 200px;
}
var test1=new Vue({
el:'#test1',
data:{
isActive:true,
hasError:false,
},
computed:{
classObj:function () {
return {
div_blue:true,'div_red':this.hasError,'size':this.hasError
}
}
}
});
运行结果:
当修改hasError
为true
时:
数组语法
<div v-bind:class="[div_blue,div_red]"></div>
data:{
div_blue: 'div_blue',
div_red: 'div_red'
}
三元运算符:
<div v-bind:class="[div_blue,isActive?div_red:'']"></div>
data:{
isActive:true,
div_blue: 'div_blue',
div_red: 'div_red'
}
使用对象:
<div v-bind:class="[div_blue,{dive_red:isActive}]"></div>
二丶style的绑定
直接设置style
样式:
<div v-bind:style="{color:fontColor,fontSize:fontSize+'px'}">测试文字</div>
data:{
fontColor:'green',
fontSize:50,
}
结果:
绑定样式对象:
<div v-bind:style="styleObject">测试文字</div>
data:{
styleObject:{
fontColor:'green',
fontSize:'50px',
}
}
使用数组绑定多个对象:
<div v-bind:style="[styleObjectBase,styleObjectAdd]">测试文字</div>
data:{
styleObject:{
fontColor:'green',
fontSize:'50px',
},
styleObject:{
'font-weight':'bold'
}
}