一、使用class樣式
1. 數組
<h1 :class="['red', 'thin']">這是一個邪惡的H1</h1>
2. 數組中使用三元表達式
<h1 :class="['red', 'thin', isactive?'active':'']">這是一個邪惡的H1</h1>
3. 數組中嵌套對象
<h1 :class="['red', 'thin', {'active': isactive}]">這是一個邪惡的H1</h1>
4. 直接使用對象
<h1 :class="{red:true, italic:true, active:true, thin:true}">這是一個邪惡的H1</h1>
二、實例
<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, classObj: { red: true, thin: true, italic: false, active: false } }, methods: {} }); </script> </body>