理解
- 在應用界面中, 某個(些)元素的樣式是變化的
- class/style 綁定就是專門用來實現動態樣式效果的技術
class 綁定
- :class='xxx'
- 表達式是字符串: 'classA'
- 表達式是對象: {classA:isA, classB: isB}
- 表達式是數組: ['classA', 'classB']
style 綁定
- :style="{ color: activeColor, fontSize: fontSize + 'px' }"
- 其中 activeColor/fontSize 是 data 屬性
編碼
<style>
.classA {
color: red;
}
.classB {
background: blue;
}
.classC {
font-size: 20px;
}
</style>
<div id="demo">
<h2>1. class 綁定: :class='xxx'</h2>
<p class="classB" :class="a">表達式是字符串: 'classA'</p>
<p :class="{classA: isA, classB: isB}">表達式是對象: {classA:isA, classB: isB}</p>
<p :class="['classA', 'classC']"> 表達式是數組: ['classA', 'classB']</p>
<h2>2. style 綁定</h2>
<p :style="{color, fontSize}">style="{ color: activeColor, fontSize: fontSize +
'px' }"</p>
<button @click="update">更新</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el : '#demo',
data : {
a: 'classA',
isA: true,
isB: false,
color: 'red',
fontSize: '20px'
},
methods : {
update () {
this.a = 'classC'
this.isA = false
this.isB = true
this.color = 'blue'
this.fontSize = '30px'
}
}
})
</script>