v-bind可以实现Class和Style的动态绑定
一、动态添加Class
对象语法:
<div>
<span class = "red" :class="{blue:isActive}">动态添加class</span>
<button @click="changeClass">切换颜色</button>
</div>
//js
data() {
return {
isActive: false,
};
},
methods: {
changeClass() {
this.isActive = !this.isActive;
},
},
//css
.red {
color: red;
}
.blue {
color: blue;
}
点击切换颜色文字颜色在红蓝之间切换
有多个class类时可以使用数组语法:
<div>
<span :class="[isActive? color='blue': color='red' , fontSize]">动态添加class</span>
<button @click="changeClass">切换颜色</button>
</div>
//js
data() {
return {
isActive: false,
fontSize: '',
color: '',
};
},
methods: {
changeClass() {
this.isActive = !this.isActive;
this.fontSize = 'changeSize';
},
},
//css
.red {
color: red;
}
.blue {
color: blue;
}
.changeSize {
font-size: 12px;
}
二、动态添加Style
对象语法:可以同时添加多个样式
<div>
<span :style="{ color, fontSize }">动态添加style</span>
<button @click="changeClass">切换颜色</button>
</div>
//js
data() {
return {
isActive: false,
color: 'red',
fontSize: '12px',
};
},
methods: {
changeClass() {
this.isActive = !this.isActive;
console.log(this.color);
this.color === 'red' ? (this.color = 'blue') : (this.color = 'red');
},
},
//css
.red { color: red; }
.blue { color: blue; }
三、用户输入颜色,动态改变字体颜色
//html代码
<ul>
<li class="liMenu" :class="idx === index ? color : ''"
@click="son(item, idx)"
v-for="(item, idx) in items" :key="idx">
{{ item }}
</li>
<input type="text" v-model="color" />
</ul>
//js代码
data() {
return {
items: ['第一个', '第二个', '第三个'],
index: 0,
color: 'red',
};
},
methods: {
son(item, idx) {
this.index = idx;
console.log(this.color);
},
},
//css代码
.red { color: red; }
.blue { color: blue; }
实现效果:当用户输入red时,点击的li变成红色;用户输入blue时,点击的li变成蓝色