黑马vue---16、vue中通过属性绑定为元素设置class类样式
一、总结
一句话总结:
这里就是为元素绑定class样式,和后面的style样式区别一下
vue中class样式绑定方式的相对于原方式的优势有可以使用三元表达式
1、vue中class样式绑定方式的相对于原方式的优势?
可以使用三元表达式:h1 :class="['thin', 'italic']"
h1 class="red thin"
2、vue中class样式绑定中 三元表达式及对象替代三元表达式?
h1 :class="['thin', 'italic', flag?'active':'']"
h1 :class="['thin', 'italic', {'active':flag} ]"
3、vue中class样式绑定中 以对象的方式绑定样式?
h1 :class="classObj"
classObj: { red: true, thin: true, italic: false, active: false }
二、内容在总结中
1、相关知识
使用class样式
- 数组
<h1 :class="['red', 'thin']">这是一个邪恶的H1</h1>
- 数组中使用三元表达式
<h1 :class="['red', 'thin', isactive?'active':'']">这是一个邪恶的H1</h1>
- 数组中嵌套对象
<h1 :class="['red', 'thin', {'active': isactive}]">这是一个邪恶的H1</h1>
- 直接使用对象
<h1 :class="{red:true, italic:true, active:true, thin:true}">这是一个邪恶的H1</h1>
2、代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 <script src="./lib/vue-2.4.0.js"></script> 10 <style> 11 .red { 12 color: red; 13 } 14 15 .thin { 16 font-weight: 200; 17 } 18 19 .italic { 20 font-style: italic; 21 } 22 23 .active { 24 letter-spacing: 0.5em; 25 } 26 </style> 27 </head> 28 29 <body> 30 <div id="app"> 31 <!-- <h1 class="red thin">这是一个很大很大的H1,大到你无法想象!!!</h1> --> 32 33 <!-- 第一种使用方式,直接传递一个数组,注意: 这里的 class 需要使用 v-bind 做数据绑定 --> 34 <!-- <h1 :class="['thin', 'italic']">这是一个很大很大的H1,大到你无法想象!!!</h1> --> 35 36 <!-- 在数组中使用三元表达式 --> 37 <!-- <h1 :class="['thin', 'italic', flag?'active':'']">这是一个很大很大的H1,大到你无法想象!!!</h1> --> 38 39 <!-- 在数组中使用 对象来代替三元表达式,提高代码的可读性 --> 40 <!-- <h1 :class="['thin', 'italic', {'active':flag} ]">这是一个很大很大的H1,大到你无法想象!!!</h1> --> 41 42 <!-- 在为 class 使用 v-bind 绑定 对象的时候,对象的属性是类名,由于 对象的属性可带引号,也可不带引号,所以 这里我没写引号; 属性的值 是一个标识符 --> 43 <h1 :class="classObj">这是一个很大很大的H1,大到你无法想象!!!</h1> 44 45 46 </div> 47 48 <script> 49 // 创建 Vue 实例,得到 ViewModel 50 var vm = new Vue({ 51 el: '#app', 52 data: { 53 flag: true, 54 classObj: { red: true, thin: true, italic: false, active: false } 55 }, 56 methods: {} 57 }); 58 </script> 59 </body> 60 61 </html>