Vue 中如何使用 class與style?

Roi Lin
4 min readSep 1, 2019

在Vue中是透過v-bind來控制class與style的呈現,如下:

v-bind:class="xxx" v-bind:style="xxx"
也可以簡寫為:class="xxx" 或 :style="xxx"

程式範例

https://codepen.io/sinyilin/pen/gOYxEYo

# Vue Instance
var vm = new Vue({
el: '#app',
data: {
//class
isBlue: true,
largeFont: 'big-size',
pinkBackground: 'pink-bg',
//style
activeColor: 'red',
fontSize: 30,
styleObject1: {
color: 'green',
fontSize: '20px',
marginBottom: '10px'
},
styleObject2: {
backgroundColor: 'cyan',
lineHeight: '2em'
}
}
});

Class

以class有幾種呈現方式:

第一種:{className : 判斷式或boolean變數(可以從vue instance取得)}

<div :class="{ blue: isBlue }"></div>

以這個例子來說,前面的blue為class名稱,當後面的判斷式或變數為true時則替該標籤加入blue的class。

第二種:使用單一vue instance的變數

<div :class="largeFont">2 Hello Vue!</div>

因此,結果呈現時會class=“big-size”。

第三種:使用陣列的方式帶入多個vue instance變數

<div :class="[largeFont, pinkBackground]"></div>

因此,結果呈現時會class=“ big-size pink-bg” 兩個。

Style

:style="{'屬性樣式':'樣式的值'}"

第一種:使用單一vue instance的變數

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

第二種:利用單一物件

<div :style="styleObject1"></div>

第三種:

<div :style="[styleObject1, styleObject2]"></div>

這邊有一個特別需要注意的地方,以style第三種的例子為順序來說,假設當styleObject1與styleObject2擁有相同屬性,也就是styleObject1有color:red,styleObject2有color:blue,後寫的屬性會蓋過先寫得的屬性。

使用注意事項

最後,在使用:class 與:style,需要特別注意一件事。

當物件的key 有-時的處理方式,例如backgroung-color。

# 方法一:會改為駝峰式來作為key值。
<div class='box' :style="{backgroundColor: 'red'}"></div>
# 方法二:將key加上''
<div class=”box” :style=”{‘background-color’: ‘red’}”></div>

原則上object的key 是不能允許有 -,但如果真的要使用,可以改為下面這樣寫,在該key以及取值的地方加上""。

objectClass: {
'rotate': false,
'bg-danger': false,
},
# 需要這樣呈現
v-model="objectClass['bg-danger']"

結論

使用:class與:style可能也還有其他種用法,上面是我列出我目前知道的用法,如果有其他種用法的也歡迎告訴我。

補充範例

當結果是true時,顯示A class,結果是false時,顯示B class。

可以參考這篇文章

以上是我的學習筆記,如果有錯誤的話也歡迎在下方留言告知我,謝謝~

--

--