在Vue中使用样式
使用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>
class样式案例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> <style> .red { color: red; } .thin { font-weight: 200; } .italic { font-style: italic; } .active { letter-spacing: 0.5em; } </style> </head> <body> <div id="app"> <!-- <h1 class="red thin">这是一个 h1 小可爱,可爱到你无法想象!</h1> --> <!-- 第一种使用方式,直接传递一个数组,注意: 这里的 class 需要使用 v-bind 做数据绑定 --> <h1 :class="['thin', 'italic']">这是一个 h1 小可爱,可爱到你无法想象!</h1> <!-- 在数组中使用三元表达式 --> <h1 :class="['thin', 'italic', flag?'active':'']">这是一个 h1 小可爱,可爱到你无法想象!</h1> <!-- 在数组中使用 对象来代替三元表达式,提高代码的可读性 --> <h1 :class="['thin', 'italic', {'active':flag} ]">这是一个 h1 小可爱,可爱到你无法想象!</h1> <!-- 在为 class 使用 v-bind 绑定 对象的时候,对象的属性是类名,由于 对象的属性可带引号,也可不带引号,所以 这里我没写引号; 属性的值 是一个标识符 --> <h1 :class="classObj">这是一个 h1 小可爱,可爱到你无法想象!</h1> </div> <script> // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { flag: true, // 这个标记用来判断一下是否也有active属性 classObj: { red: true, thin: true, italic: false, active: this.flag } }, methods: {} }); </script> </body> </html>
使用内联样式
- 直接在元素上通过
:style
的形式,书写样式对象
<h1 :style="{color: 'red', 'font-size': '40px'}">这是一个善良的H1</h1>
- 将样式对象,定义到
data
中,并直接引用到:style
中
- 在data上定义样式:
data: { h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' } }
- 在元素中,通过属性绑定的形式,将样式对象应用到元素中:
<h1 :style="h1StyleObj">这是一个善良的H1</h1>
- 在
:style
中通过数组,引用多个data
上的样式对象
- 在data上定义样式:
data: { h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }, h1StyleObj2: { fontStyle: 'italic' } }
- 在元素中,通过属性绑定的形式,将样式对象应用到元素中:
<h1 :style="[h1StyleObj, h1StyleObj2]">这是一个善良的H1</h1>
内联样式案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="app"> <!-- 对象就是无序键值对的集合 --> <h1 :style="styleObj1">这是第一个h1</h1> <h1 :style="[ styleObj1, styleObj2 ]">这是第二个h1</h1> </div> <script> // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { styleObj1: { color: 'red', 'font-weight': 200 }, styleObj2: { 'font-style': 'italic' } }, methods: { } }); </script> </body> </html>