<h2 v-bind:class="{css类名1: true|false, css类名2: true|false}">{{message}}</h2>
问题:我们使用了v-bind:class,那么class属性还能不能用了?
答:可以,完全不耽误,vue会帮你将二者合并
<h2 v-bind:class="{css类名1: true|false, css类名2: true|false}" class="css类名3">{{message}}</h2>
实现一个简单的需求:为文字增加颜色,并点击按钮实现颜色的切换。
按钮实现颜色的切换
<style>
.green {
color: green;
}
.red {
color: red;
}
</style>
<div id="app">
<h3 v-bind:class="getColour()">{{message}}</h3>
<button @click="changeColor">点击按钮更换颜色</button>
</div>
<!--从CDN引入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: '“手里没有剑和有剑不用不是一回事”。尊严只在剑锋之上,真理只在大炮射程之内。',
isRed: true, //默认显示红色
isGreen: false
},
methods: {
getColour(){
return {
red : this.isRed,
green: this.isGreen
}
},
changeColor(){
this.isRed = !this.isRed
this.isGreen = !this.isGreen
}
}
})
</script>
浏览器效果展示
v-bind绑定class属性
<style>
.green {
color: green;
}
.red {
color: red;
}
.bold {
font-weight: 800;
font-size: 28px;
}
</style>
<div id="app">
<h3 v-bind:class="cssArray">{{message}}</h3>
<button @click="changeColor">点击按钮更换颜色</button>
</div>
<!--从CDN引入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: '“回忆是一条没有尽头的路,一切以往的春天都不复存在,就连那最坚韧而又狂乱的爱情归根结底也不过是转瞬即逝的现实。\n',
// isRed: true, //默认显示红色
// isGreen: false
cssArray: ['bold','red'] //默认室蓝色
},
methods: {
changeColor(){
if(this.cssArray[1] !== 'red'){ //如果不是红色
this.cssArray.pop();
this.cssArray.push('red');
// this.cssArray[1] = 'red' //这种写法不是响应式的,数据发生变化时,页面显示的颜色不会改变。
}else {
this.cssArray.pop();
this.cssArray.push('green');
}
}
}
})
</script>
浏览器页面展示:
我们使用数组的pop()和push()方法去操作数组元素,而不是使用this.cssArray[1] = 'red'
直接操作数组。因为这种通过下标操作数组的方式不是响应式的,也就是说虽然数组元素的值会发生变化,但不会导致页面颜色发生切换。
所以,当我们希望通过操作数据影响页面显示内容及显示效果的时候,要使用数组相关的函数,不能直接使用数组下标操作数据。下面列举一下经常用到的响应式的数组操作函数:
- push(param…) 加入元素到数组的尾部
- pop() 从数组的尾部弹出一个元素