Vue class 绑定样式
Vue 绑定样式有三种:字符串写法、数组写法、对象写法
字符串写法
适用于:样式类名不确定,需要动态指定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定样式</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- 绑定 class 样式 字符串写法 -->
<div class="basic" :class="mood" @click="changeMood"></div>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
mood: 'blue'
},
methods: {
changeMood() {
this.mood = 'red'
}
}
})
</script>
<style>
.basic {
height: 100px;
width: 100px;
}
.blue {
background: blue;
}
.red {
background: red;
}
.green {
background: green;
}
</style>
</html>
让三种颜色随机切换
methods: {
changeMood() {
const arr = ['red', 'blue', 'green']
const index = Math.floor(Math.random() * 3)
this.mood = arr[index]
}
}
数组写法
适用于:要绑定的样式个数不确定、名字也不确定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定样式</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- 绑定 class 样式 数组写法 -->
<div class="basic" :class="classArr"></div>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
mood: 'blue',
classArr: ['border1', 'border2', 'border3']
},
methods: {
changeMood() {
// this.mood = 'red'
const arr = ['red', 'blue', 'green']
const index = Math.floor(Math.random() * 3)
this.mood = arr[index]
}
}
})
</script>
<style>
.basic {
height: 100px;
width: 100px;
}
.border1 {
border-style: solid;
}
.border2 {
border-color: red;
}
.border3 {
border-radius: 30px;
}
</style>
</html>
对象写法
适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定样式</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- 绑定 class 样式 对象写法 -->
<div class="basic" :class="classObj"></div>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
mood: 'blue',
classObj: {
border1:true,
border2:false,
border3:true
}
},
methods: {
changeMood() {
// this.mood = 'red'
const arr = ['red', 'blue', 'green']
const index = Math.floor(Math.random() * 3)
this.mood = arr[index]
}
}
})
</script>
<style>
.basic {
height: 100px;
width: 100px;
}
.border1 {
border-style: solid;
}
.border2 {
border-color: red;
}
.border3 {
border-radius: 30px;
}
</style>
</html>
总结
- 绑定 class 样式 字符串写法 适用于:样式类名不确定,需要动态指定
- 绑定 class 样式 数组写法 适用于:要绑定的样式个数不确定、名字也不确定
- 绑定 class 样式 对象写法 适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用