4.1 字符串/数组/对象写法
css样式:
<style>
.bgcRed {
background-color: red;
}
.bgcBlue {
background-color: blue;
}
.bgcYellow {
background-color: yellow;
}
.basic {
width: 200px;
height: 100px;
border: 1px solid black;
}
.s1 {
font-size: 50px;
}
.s2 {
border-radius: 50px;
border: 3px solid yellow;
}
.s3 {
background: green;
}
</style>
HTML代码:
<div id="el">
<!-- 绑定class样式: 字符串写法,适用于: 样式的类名不确定,需要动态指定 -->
<div class="basic" :class="bgc" @click="changeBgc1"></div>
<br>
<!-- 绑定class样式: 数组写法,适用与: 要绑定的样式个数不确定,名字也不确定-->
<div class="basic" :class="bgcArr" @click="changeBgc2">呓语</div>
<br>
<!-- 绑定class样式: 对象写法,适用与: 要绑定的样式个数确定,名字也确定,但要动态决定用不用-->
<div class="basic" :class="bgcObj" @click="changeBgc3">呓语</div>
</div>
Vue代码:
<script>
const vm = new Vue({
el: "#el",
data: {
bgc: "bgcRed",
bgcArr: ['s1', 's2'],
bgcObj: {
s1: false,
s2: false,
s3: true
}
},
methods: {
changeBgc1() {
this.bgc = "bgcBlue"
},
changeBgc2() {
setTimeout(() => {
this.bgcArr.push("s3")
setTimeout(() => {
vm.bgcArr.shift();
setTimeout(() => {
vm.bgcArr.push("s1")
}, 2000)
}, 2000)
}, 2000)
},
changeBgc3() {
this.bgcObj.s1 = true;
this.bgcObj.s2 = true;
}
}
})
</script>
Style应用
HTML:
<!-- 绑定style样式: 对象写法-->
<div class="basic" :style="styleObj">呓语</div>
<br><br>
<!-- 绑定style样式: 数组写法-->
<div class="basic" :style="styleArr">呓语</div>
Vue
styleObj: {
fontSize: "50px",
color: "blue",
backgroundColor: "gray"
},
styleArr: [
{
borderRadius: "15px",
backgroundColor: "red",
width: "300px"
}
]