Vue从入门到实战:绑定HTML class
来自CloudWiki
背景
HTML元素有两个设置样式的属性,class和style,
在Vue.js中可以用v-bind指令来处理它们,并做了增强。
对象语法
可以给v-bind:class传递一个对象,以动态地切换class
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class绑定</title> <style> .static { border: solid 2px black; } .active { width: 100px; height: 100px; background: green; } </style> </head> <body> <div id = "app"> <div class="static" v-bind:class="{ active: isActive }"></div> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { isActive: true, } }); </script> </body> </html>
粗体显示的代码中active这个class存在与否取决于数据属性isActive的值,isActive 计算为真时则这个样式起作用
也可以在对象中传入更多属性来动态切换多个class.此外,v-bind:class也可以和普通的class属性一起使用
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class绑定</title> <style> .static { border: solid 2px black; } .active { width: 100px; height: 100px; background: green; } .text-danger { background: red; } </style> </head> <body> <div id = "app"> <div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { isActive: true, hasError: false, } }); </script> </body> </html>
绑定的数据对象如果较为复杂,可以在数据属性中单独定义一个对象,然后绑定它
<div v-bind:class="classObject"></div> data: { classObject: { active: true, 'text-danger': false } }
数组语法
除了给v-bind:class传递对象外,也可以传递一个数组,应用一个class列表。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class绑定</title> <style> .static { border: solid 2px black; } .active { width: 100px; height: 100px; background: green; } .text-danger { background: red; } </style> </head> <body> <div id = "app"> <div v-bind:class="[activeClass, errorClass]"></div> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { activeClass: 'active', errorClass: 'text-danger' } }); </script> </body> </html>
如果你也想根据条件切换列表中的 class,可以用三元表达式:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
这样写将始终添加 errorClass,但是只有在 isActive 是 truthy[1] 时才添加 activeClass。
不过,当有多个条件 class 时这样写有些繁琐。所以在数组语法中也可以使用对象语法:
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
在组件上使用
这个章节假设你已经对 Vue 组件有一定的了解。当然你也可以先跳过这里,稍后再回过头来看。
当在一个自定义组件上使用 class property 时,这些 class 将被添加到该组件的根元素上面。这个元素上已经存在的 class 不会被覆盖。
例如,如果你声明了这个组件:
Vue.component('my-component', { template: '<p class="foo bar">Hi</p>' })
然后在使用它的时候添加一些 class:
<my-component class="baz boo"></my-component>
HTML 将被渲染为:
<p class="foo bar baz boo">Hi</p>
对于带数据绑定 class 也同样适用:
<my-component v-bind:class="{ active: isActive }"></my-component>
当 isActive 为 truthy[1] 时,HTML 将被渲染成为:
<p class="foo bar active">Hi</p>