<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>
-
直接在元素上通過
: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> <head> <meta charset="utf-8"> <title></title> <script src="js/vue-2.4.0.js" type="text/javascript" charset="utf-8"></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> <!-- 對象就是無序鍵值對的集合 --> <!-- <h1 :style="styleObj1">這是一個h1</h1> --> <!-- 添加多個對象,可以放到數組中 --> <h1 :style="[ styleObj1, styleObj2 ]">這是一個h1</h1> </div> <script> // 創建 Vue 實例,得到 ViewModel var vm = new Vue({ el: '#app', data: { flag: true, classObj: {red: true,thin: true,italic: false,active: false}, styleObj1:{ color:"red","font-size":"28px"}, styleObj1:{ 'font-weight': 200},//屬性有橫線的要加雙引號 }, methods: {} }); </script>