引子
v-bind 主要用于屬性綁定,Vue官方提供了一個簡寫方式 :bind,例如:
<!-- 完整語法 --><a v-bind:href="url"></a><!-- 縮寫 --><a :href="url"></a>
一、概述
v-bind 主要用于屬性綁定,比方你的class屬性,style屬性,value屬性,href屬性等等,只要是屬性,就可以用v-bind指令進行綁定。
示例:
<!-- 綁定一個屬性 --><img v-bind:src="imageSrc"><!-- 縮寫 --><img :src="imageSrc"><!-- 內聯字符串拼接 --><img :src="'/path/to/images/' + fileName"><!-- class 綁定 --><div :class="{ red: isRed }"></div><div :class="[classA, classB]"></div><div :class="[classA, { classB: isB, classC: isC }]"><!-- style 綁定 --><div :style="{ fontSize: size + 'px' }"></div><div :style="[styleObjectA, styleObjectB]"></div><!-- 綁定一個有屬性的對象 --><div v-bind="{ id: someProp, 'other-attr': otherProp }"></div><!-- 通過 prop 修飾符綁定 DOM 屬性 --><div v-bind:text-content.prop="text"></div><!-- prop 綁定。“prop”必須在 my-component 中聲明。--><my-component :prop="someThing"></my-component><!-- 通過 $props 將父組件的 props 一起傳給子組件 --><child-component v-bind="$props"></child-component><!-- XLink --><svg><a :xlink:special="foo"></a></svg>二、綁定 HTML Class
對象語法
我們可以傳給 v-bind:class 一個對象,以動態地切換 class
<div v-bind:class="{ active: isActive }"></div>上面的語法表示 active 這個 class 存在與否將取決于數據屬性 isActive 的 truthiness
你可以在對象中傳入更多屬性來動態切換多個 class。此外,v-bind:class 指令也可以與普通的 class 屬性共存。當有如下模板:
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div> 和如下 datadata: { isActive: true, hasError: false}結果渲染為:
<div class="static active"></div>
當 isActive 或者 hasError 變化時,class 列表將相應地更新。例如,如果 hasError 的值為 true,class 列表將變為 "static active text-danger"
綁定的數據對象不必內聯定義在模板里
<div v-bind:class="classObject"></div>data: { classObject: { active: true, 'text-danger': false }}渲染的結果和上面一樣。我們也可以在這里綁定一個返回對象的計算屬性。這是一個常用且強大的模式:
新聞熱點
疑難解答
圖片精選