<style>
.red{
color: red;
}
.thin{
font-weight: 200;
}
.italic{
font-style: italic;
}
.active{
letter-spacing: 0.5em;
}
</style>
</head>
<body>
<div id="app">
<!-- 第一種使用方式,直接傳遞一個數組,注意:這裏的 class 需要使用 v-bind 做數據綁定-->
<!-- <h1 :class="['red', 'thin', 'italic']">大大的H1</h1> -->
<!-- 在數組中使用三元表達式 -->
<!-- <h1 :class="[flag?'active':'', 'thin', 'italic']">大大的H1</h1> -->
<!-- 在數組中使用對象來代替三元表達式,提高代碼可讀性 -->
<!-- <h1 :class="['thin', 'italic', {'active': flag}]">大大的H1</h1> -->
<!-- 在爲 class 使用 v-bind 綁定對象的時候,對象的屬性是類名,由於對象的屬性可帶引號,也可不帶引號,所以這裏沒寫引號,屬性的值是一個標識符 -->
<h1 :class="classObj">大大的H1</h1>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
classObj: { red:true, thin: true, italic: false, active: false }
},
methods: {
}
})
</script>
</body>
使用v-bind
綁定class
改變樣式
['red', 'thin', 'italic']
:直接傳遞一個數組,數組中的元素用引號括起來,會在style
中尋找樣式- 三元表達式
[flag?'active':'', 'thin', 'italic']
:元素不加引號,會在Vue實例的data屬性中尋找值 - 在數組中使用對象
['thin', 'italic', {'active': flag}]
:在Vue實例的data屬性中尋找flag的值,根據flag的值決定是否加上active類名 - 爲 class 使用 v-bind 綁定對象:對象的屬性是類名,由於對象的屬性可帶引號,也可不帶引號,所以這裏沒寫引號,屬性的值是一個標識符