class样式绑定
通过class绑定实现开关灯样式
css样式
<style>
.kai {
width: 100px;
height: 100px;
background-color: rgb(130, 141, 151);
}
.guan {
width: 100px;
height: 100px;
background-color: black;
}
.deng {
font-size: 40px;
}
</style>
v-bind:class 指令也可以与普通的 class 属性共存
v-bind指令绑定的class属性是一个对象 属性为类名 值为任意一个表达式 表达式会被判断为布尔值 当值为true时 对应是类名才会生效 否则不会生效
<div :class="{kai:a1,guan:a2}">灯</div>
数组语法,这样写将始终添加 deng,但是只有在a1 a2是真值时才添加对应类名
<div :class="[{kai:a1,guan:a2},'deng']">灯</div>
完整代码:
<body>
<div class="box">
<button v-text="text" @click="fn"></button>
<div :class="{kai:a1,guan:a2}">灯</div>
<div :class="[{kai:a1,guan:a2},'deng']">灯</div>
</div>
<script>
new Vue({
el: ".box",
data: {
text: "关灯",
a1: true,
a2: false,
},
methods: {
// Vue实例对象中 this指向VUe对象
fn() {
this.a1 = !this.a1;
this.a2 = !this.a2;
if (this.text == "关灯") {
this.text = "开灯";
} else {
this.text = "关灯";
}
},
},
});
</script>
style样式绑定
<body>
<div class="box">
<p :style="{color:iscolor,fontSize:num+'px'}">
通过style绑定实现开样式改变
</p>
<p :style="[{color:iscolor,fontSize:num+'px'},size]">
数组语法,可以将多个样式对象应用到同一个元素上
</p>
</div>
<script>
new Vue({
el: ".box",
data: {
size: { fontSize: 40 + "px" },
iscolor: "red",
num: 10,
},
});
</script>
</body>