Vue绑定class


 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7   <title>Document</title>
 8   <style>
 9     .add-bg {
10       background: cyan;
11     }
12     .add-color {
13       color: #fff;
14     }
15     .add-fontsize {
16       font-size: 18px;
17     }
18   </style>
19   <!-- vue.js 引入 -->
20   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
21 </head>
22 <body>
23   <div id="app">
24     <!-- 1、 -->
25     <div class="add-fontsize" :class="{'add-bg': isActive, 'add-color': addColor}">bind class</div>
26     <!-- 虽然说是写了三个class,并且还分成了两类,但是Vue会很智能的将这两类合并为我们想要的效果 -->
27 
28 
29     <!-- 2、 -->
30     <!-- 或使用三元的方式去操控class -->
31     <div :class="[addColor ? 'add-color' : 'add-bg', 'add-fontsize']">use 三元</div>
32     <!-- 这里的add-fontsize始终都有 -->
33 
34 
35     <!-- 3、 -->
36     <!-- 使用对象的方式去操控class -->
37     <div :class="[{'add-bg': isActive}, 'add-fontsize']">use object</div>
38     <!-- 这里的add-fontsize始终都有 -->
39     <!-- 当对象中的class属性是单独的一串字符,没有其它横杠、下划线等特殊符号时,可省略掉单引号 -->
40   </div>
41 
42   <script>
43     var app = new Vue({
44       el: '#app',
45       data () {
46         return {
47           isActive: false, // 改为true时就会展示对应的背景色
48           addColor: false // 改为true时就会展示字体对应的颜色
49         }
50       }
51     })
52   </script>
53 </body>
54 </html>

结果如下:

Vue

原文地址:https://www.cnblogs.com/cq-0715/p/9795190.html