在Vue中使用樣式
使用class樣式
- 數(shù)組
<h1 :class="['red', 'thin']">這是一個邪惡的H1</h1>
- 數(shù)組中使用三元表達式
<h1 :class="['red', 'thin', isactive?'active':'']">這是一個邪惡的H1</h1>
- 數(shù)組中嵌套對象
<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> -->
<!-- 第一種使用方式,直接傳遞一個數(shù)組,注意: 這里的 class 需要使用 v-bind 做數(shù)據(jù)綁定 -->
<h1 :class="['thin', 'italic']">這是一個 h1 小可愛,可愛到你無法想象!</h1>
<!-- 在數(shù)組中使用三元表達式 -->
<h1 :class="['thin', 'italic', flag?'active':'']">這是一個 h1 小可愛,可愛到你無法想象!</h1>
<!-- 在數(shù)組中使用 對象來代替三元表達式,提高代碼的可讀性 -->
<h1 :class="['thin', 'italic', {'active':flag} ]">這是一個 h1 小可愛,可愛到你無法想象!</h1>
<!-- 在為 class 使用 v-bind 綁定 對象的時候,對象的屬性是類名,由于 對象的屬性可帶引號,也可不帶引號,所以 這里我沒寫引號; 屬性的值 是一個標識符 -->
<h1 :class="classObj">這是一個 h1 小可愛,可愛到你無法想象!</h1>
</div>
<script>
// 創(chuàng)建 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>
使用內(nèi)聯(lián)樣式
- 直接在元素上通過
:style
的形式,書寫樣式對象
<h1 :style="{color: 'red', 'font-size': '40px'}">這是一個善良的H1</h1>
- 將樣式對象,定義到
data
中,并直接引用到 :style
中
data: {
h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }
}
- 在元素中,通過屬性綁定的形式,將樣式對象應(yīng)用到元素中:
<h1 :style="h1StyleObj">這是一個善良的H1</h1>
- 在
:style
中通過數(shù)組,引用多個 data
上的樣式對象
data: {
h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' },
h1StyleObj2: { fontStyle: 'italic' }
}
- 在元素中,通過屬性綁定的形式,將樣式對象應(yīng)用到元素中:
<h1 :style="[h1StyleObj, h1StyleObj2]">這是一個善良的H1</h1>
內(nèi)聯(lián)樣式案例

<!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>
// 創(chuàng)建 Vue 實例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
styleObj1: {
color: 'red',
'font-weight': 200
},
styleObj2: {
'font-style': 'italic'
}
},
methods: {
}
});
</script>
</body>
</html>