数据绑定的一个常见需求场景是操纵元素的 CSS class 列表和内联样式。因为 class 和 style 都是 attribute,我们可以和其他 attribute 一样使用 v-bind 将它们和动态的字符串绑定。但是,在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的。因此,Vue 专门为 class 和 style 的 v-bind 用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。
2.4.1 class 绑定
2.4.1.1 绑定字符串
适用于样式的名字不确定,需要动态指定。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>class 绑定字符串形式</title><script src="../js/vue.js"></script><style>.static{border: 1px solid black;background-color: beige;}.big{width: 200px;height: 200px;}.small{width: 100px;height: 100px;}</style></head><body><div id="app"><h1>{{msg}}</h1><div class="static" :class="c1"></div></div><script>const vm = new Vue({el : '#app',data : {msg : 'class 绑定字符串形式',c1 : 'small'}})</script></body></html>
运行效果:
使用 vue 开发者工具修改 c1 的 small 为 big:
通过测试可以看到样式完成了动态的切换。
2.4.1.2 绑定数组
适用于绑定的样式名字不确定,并且个数也不确定。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>class 绑定数组形式</title><script src="../js/vue.js"></script><style>.static{border: 1px solid black;}.active{background-color: green;}.text-danger{color: red;}</style></head><body><div id="app"><h1>{{msg}}</h1><div class="static" :class="['active','text-danger']">数组形式</div><br><br><div class="static" :class="[activeClass,errorClass]">数组形式</div><br><br><div class="static" :class="classArray">数组形式</div></div><script>const vm = new Vue({el : '#app',data : {msg : 'class 绑定数组形式',activeClass : 'active',errorClass : 'text-danger',classArray : ['active', 'text-danger']}})</script></body></html>
运行效果:
使用 vue 开发者工具删除数组中的一个样式:
2.4.1.3 绑定对象
适用于样式名字和个数都确定,但是要动态决定用或者不用。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>class 绑定对象形式</title><script src="../js/vue.js"></script><style>.static{border: 1px solid black;}.active{background-color: green;}.text-danger{color: red;}</style></head><body><div id="app"><h1>{{msg}}</h1><div class="static" :class="{active : true, 'text-dang: true}">对象形式</div><br><br><div class="static" :class="classObject">对象形式iv></div><script>const vm = new Vue({el : '#app',data : {msg : 'class 绑定对象形式',classObject : {active : true,'text-danger' : false}}})</script></body></html>
运行效果:
使用 vue 开发者工具修改 text-danger 为 true:
2.4.2 style 绑定
2.4.2.1 绑定对象
<div id="app"><h1>{{msg}}</h1><!-- 静态写法 --><div class="static" style="font-size: 20px;">对象形式</div><br><br><!-- 动态写法 1 --><div class="static" :style="{fontSize: 40 + 'px'}">对象形式</div><br><br><!-- 动态写法 2 --><div class="static" :style="styleObject">对象形式</div><br><br></div><script>const vm = new Vue({el : '#app',data : {msg : 'style 绑定对象形式',styleObject : {fontSize : '40px'}}})</script>
2.4.2.2 绑定数组
<div id="app"><h1>{{msg}}</h1><!-- 静态写法 --><div class="static" style="font-size: 40px; color: red;">数组形式</div><br><br><!-- 动态写法 1 --><div class="static" :style="[{fontSize:'40px'},{color:'red'}]">数组形式</div><br><br><!-- 动态写法 2 --><div class="static" :style="styleArray">对象形式</div><br><br></div><script>const vm = new Vue({el : '#app',data : {msg : 'style 绑定对象形式',styleArray : [{fontSize:'40px'},{color:'red'}]}})</script>
