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>