當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js v-bind用法及代碼示例

將一個或多個屬性或組件屬性動態綁定到表達式。

速記: :或者.(使用時.prop修飾符)

期望: any (with argument) | Object (without argument)

參數: attrOrProp (optional)

修飾符:

  • .camel - 將 kebab-case 屬性名稱轉換為 camelCase。
  • .prop - 強製將綁定設置為 DOM 屬性。 3.2+
  • .attr - 強製將綁定設置為 DOM 屬性。 3.2+

用法:

當用於綁定classstyle 屬性時,v-bind 支持其他值類型,例如數組或對象。有關更多詳細信息,請參閱下麵的鏈接指南部分。

在元素上設置綁定時,Vue 默認使用in 運算符檢查檢查元素是否具有定義為屬性的鍵。如果定義了屬性,Vue 會將值設置為 DOM 屬性而不是屬性。這在大多數情況下應該有效,但您可以通過顯式使用 .prop.attr 修飾符來覆蓋此行為。這有時是必要的,尤其是在 working with custom elements 時。

用於組件 prop 綁定時,必須在子組件中正確聲明該 prop。

不帶參數使用時,可用於綁定包含屬性 name-value 對的對象。請注意,在此模式下 classstyle 不支持數組或對象。

例子:

<!-- bind an attribute -->
<img v-bind:src="imageSrc" />

<!-- dynamic attribute name -->
<button v-bind:[key]="value"></button>

<!-- shorthand -->
<img :src="imageSrc" />

<!-- shorthand dynamic attribute name -->
<button :[key]="value"></button>

<!-- with inline string concatenation -->
<img :src="'/path/to/images/' + fileName" />

<!-- class binding -->
<div :class="{ red: isRed }"></div>
<div :class="[classA, classB]"></div>
<div :class="[classA, { classB: isB, classC: isC }]"></div>

<!-- style binding -->
<div :style="{ fontSize: size + 'px' }"></div>
<div :style="[styleObjectA, styleObjectB]"></div>

<!-- binding an object of attributes -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

<!-- prop binding. "prop" must be declared in the child component. -->
<MyComponent :prop="someThing" />

<!-- pass down parent props in common with a child component -->
<MyComponent v-bind="$props" />

<!-- XLink -->
<svg><a :xlink:special="foo"></a></svg>

.prop 修飾符還有一個專用的簡寫,.

<div :someProperty.prop="someObject"></div>

<!-- equivalent to -->
<div .someProperty="someObject"></div>

.camel 修飾符允許在使用 in-DOM 模板時將 v-bind 屬性名稱駱駝化,例如SVG viewBox 屬性:

<svg :view-box.camel="viewBox"></svg>

如果您使用字符串模板,或使用構建步驟預編譯模板,則不需要.camel

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 v-bind。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。