目录
v-bind:class设置样式
1.为v-bind:class设置一个对象,实现动态切换class
示例
html:
<div id="app">
<div v-bind:class="{'box':xianshi}">hello</div>
</div>
css:
.box {color: yellow;}
js:
new Vue({
el: "#app",
data: {xianshi: true}//false就不显示
});
2.在对象中传入更多属性,动态切换更多的class
示例
html:
<div id="app">
<div v-bind:class="{'box1':yangshi1,'box2':yangshi2}">hello</div>
</div>
css:
.box1 {color: red;}
.box2 {color: blue;}
js:
new Vue({
el: "#app",
data: {
yangshi1: true,
yangshi2: false
/*哪个true就输入哪个,且后面的样式权重高,都是false则不显示样式*/
}
});
3.直接绑定数据里的一个对象
示例:
html:
<div id="app">
<div v-bind:class="obj">hello</div>
</div>
css:
.box {color: red;}
js:
new Vue({
el: "#app",
data: {obj:{"box":true}}
});
4.绑定返回对象的计算属性
示例:
html:
<div id="app"><div v-bind:class="obj">hello</div></div>
css:
.box1 {background: green;}
.box2 {background: red;}
js:
new Vue({
el: '#app',
data: {
show1: true,
judge: {
show2: false,
error: 'cuowu'
}
},
computed: {//计算属性
obj: function() {
return {
box1: this.show1 && !this.judge.show2,
box2: this.judge.show2 && this.judge.error === 'cuowu',
}
}
}
})
5.把一个数组传给v-bind:class
示例
html:
<div id="app">
<div v-bind:class="[sub1,sub2]">hello</div>
</div>
css:
.box1 {background: green;}
.box2 {background: red;}
js:
new Vue({
el: "#app",
data: {
sub1: 'box1',
sub2: 'box2'
}
});
输出:
输出:
hello
6.使用三元表达式来切换列表中的class
示例
html:
<div id="app">
<div v-bind:class="[sub1,judge?sub2:'']">hello</div>
</div>
css:(同上)
js:
new Vue({
el: "#app",
data: {
judge: true,
sub1: "box1",
sub2: "box2"
}
});
v-bind:style设置样式
1.style直接设置样式
示例
html:
<div id="app">
<div v-bind:style="{color:c,fontSize:fs+'px'}">hello</div>
</div>
js:
new Vue({
el: "#app",
data: {
c: 'red',
fs: 18
}
});
2.直接绑定到一个样式对象上
示例
html:
<div id="app">
<div v-bind:style="Obj">hello</div>
</div>
js:
new Vue({
el: "#app",
data: {
Obj: {
color: 'red',
fontSize: '28px'
}
}
});
3.使用数组将多个样式对象应用到一个元素上
示例
html:
<div id="app">
<div v-bind:style="[sub1,sub2]">hello</div>
</div>
js:
new Vue({
el: "#app",
data: {
sub1: {color: "green"},
sub2: {
fontSize: "20px",
"font-weight": "bolder"
}
}
});
*当v-bind:style使用需要特定前缀放的css属性(如:transform)时,vue会自动检测并添加相应前缀