在我沒看這以前,我以爲要寫綁定class ,應該像綁定數據同樣這麼寫html
class ={{class-a}}
看官方教程時,不推薦這麼寫,推薦這樣vue
v-bind:class="{ 'class-a': isA, 'class-b': isB }"
官方的解釋,我以爲仍是挺接地氣的,最起碼我能看的懂。數組
數據綁定一個常見需求是操做元素的 class 列表和它的內聯樣式。由於它們都是屬性,咱們能夠用 v-bind
處理它們:咱們只須要計算出表達式最終的字符串。不過,字符串拼接麻煩又易錯。所以,在v-bind
用於 class
和 style
時,Vue.js 專門加強了它。表達式的結果類型除了字符串以外,還能夠是對象或數組。ide
能夠這樣:https://jsfiddle.net/miloer/36ek1uco/ui
也能夠這樣:https://jsfiddle.net/miloer/36ek1uco/1/spa
https://jsfiddle.net/miloer/36ek1uco/2/.net
我以爲在樣式裏用表達式判斷,這麼作挺有創意的,不過我的感受這麼作又繁瑣了點,不過官方說:雙向綁定
當有多個條件 class 時這樣寫有些繁瑣。在 1.0.19+ 中,能夠在數組語法中使用對象語法:code
<div v-bind:class="[classA, { classB: isB, classC: isC }]">
這樣是否是好多了。component
這個和綁定HTMLCLASS 方法差很少。
https://jsfiddle.net/miloer/36ek1uco/3/
https://jsfiddle.net/miloer/36ek1uco/4/
這個我以爲挺方便的,當使用v-bind:style 須要添加前綴CSS時,Vue.js 會自動偵測並添加相應的前綴。
:
* (with argument) | Object (without argument)
attrOrProp (optional)
.sync
- 雙向綁定,只能用於 prop 綁定。.once
- 單次綁定,只能用於 prop 綁定。.camel
- 將綁定的特性名字轉回駝峯命名。只能用於普通 HTML 特性的綁定,一般用於綁定用駝峯命名的 SVG 特性,好比 viewBox
。在綁定 class
或 style
時,支持其它類型的值,如數組或對象。
在綁定 prop 時,prop 必須在子組件中聲明。能夠用修飾符指定不一樣的綁定類型。
沒有參數時,能夠綁定到一個對象。注意此時 class
和 style
綁定不支持數組和對象。
<!-- 綁定 attribute -->
<img v-bind:src="imageSrc"> <!-- 縮寫 --> <img :src="imageSrc"> <!-- 綁定 class --> <div :class="{ red: isRed }"></div> <div :class="[classA, classB]"></div> <div :class="[classA, { classB: isB, classC: isC }]"></div> <!-- 綁定 style --> <div :style="{ fontSize: size + 'px' }"></div> <div :style="[styleObjectA, styleObjectB]"></div> <!-- 綁定到一個對象 --> <div v-bind="{ id: someProp, 'other-attr': otherProp }"></div> <!-- prop 綁定,"prop" 必須在 my-component 組件內聲明 --> <my-component :prop="someThing"></my-component> <!-- 雙向 prop 綁定 --> <my-component :prop.sync="someThing"></my-component> <!-- 單次 prop 綁定 --> <my-component :prop.once="someThing"></my-component> |