Skip to content

属性绑定

基本语法

vue
<div v-bind:id="dynamicId"></div>

v-bind 指令指示 Vue 将元素的 id attribute 与组件的 dynamicId 属性保持一致。

如果绑定的值是 null 或者 undefined,那么该 attribute 将会从渲染的元素上移除。

简写

vue
<div :id="dynamicId"></div>

同名简写

警告

仅支持 3.4 版本及以上

如果 attribute 的名称与绑定的 JavaScript 变量的名称相同,那么可以进一步简化语法,省略 attribute 值:

vue
<!-- 与 :id="id" 相同 -->
<div :id></div>

<!-- 这也同样有效 -->
<div v-bind:id></div>

布尔型 Attribute

布尔型 attribute 依据 true / false 值来决定 attribute 是否应该存在于该元素上。disabled 就是最常见的例子之一。

v-bind 在这种场景下的行为略有不同:

vue
<button :disabled="isButtonDisabled">Button</button>

isButtonDisabled 为真值或一个空字符串 (即 <button disabled="">) 时,元素会包含这个 disabled attribute。而当其为其他假值时 attribute 将被忽略。

动态绑定多个值

如果你有像这样的一个包含多个 attribute 的 JavaScript 对象:

ts
const objectOfAttrs = {
  id: 'container',
  class: 'wrapper',
  style: 'background-color:green'
}

通过不带参数的 v-bind,你可以将它们绑定到单个元素上:

vue
<div v-bind="objectOfAttrs"></div>