当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。