vue绑定class的几种方式
vue绑定class的几种方式
1.对象语法
在对象上绑定class属性,来控制class 的几种状态。
<body> hello world!</h1></div></script><script> var app = new Vue({ el: '#app', data: { isActive: true } })</script></body>
2.数组语法
将class的属性值组成一个数组来控制class的各种属性,当class 需要有多个属性的时候就要用数组语法来绑定其中的值,这样做的好处是有利于动态修改class的值。
<html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> .active{ color: red; width: 100px; height: 300px; } </style></head><body> <div :class="[isActive ? activeCls : '', errorCls]"></div></div></script><script> // 绑定数组运算符号 var app = new Vue({ el: '#app', data: { isActive: false, activeCls: 'active', errorCls: 'error' } })</script></body></html>
3.在组件上使用
如果在组件上使用class 或者:clas上,样式规则会直接应用到这个组件的跟元素上,如下所示:
<body> <my-component :class="{'active': isActive}"></my-component></div></script><script> // 自定义组件 Vue.component('my-component',{ template: '这是一些文本文章!!!!
' }); // 绑定数组运算符号 var app = new Vue({ el: '#app', data: { isActive: false } })</script>
最终渲染后的结果为
<p class="article">这是一些文本文章!!!!</p>
这种用法仅仅适用于自定义组件的外层是一个根元素,否则会无效,当不满足这种条件或者给具体的子元素设置类名的时候应当使用组件的props来传递。