在 Vue3 中,Attribute 绑定是一个核心概念,用于将组件的数据动态绑定到 HTML 元素的属性上。最常用的方式是使用 v-bind
指令,也可以使用简写形式 :
。
基本用法
- 完整语法 (v-bind)
vue
xml
<template>
<img v-bind:src="imageUrl" />
</template>
<script setup>
const imageUrl = "https://picsum.photos/200/300"
</script>
- 简写语法 (:)
vue
xml
<template>
<img :src="imageUrl" />
</template>
动态绑定多个属性
可以使用对象语法同时绑定多个属性:
vue
xml
<template>
<div :attrs="divAttributes"></div>
</template>
<script setup>
const divAttributes = {
id: "my-div",
class: "container",
title: "这是一个容器"
}
</script>
绑定 class 和 style 的特殊处理
Vue 对 class
和 style
有特殊处理,可以使用对象或数组语法:
vue
xml
<template>
<!-- class 绑定 -->
<div :class="{ active: isActive, 'text-danger': hasError }"></div>
<!-- style 绑定 -->
<div :style="{ color: textColor, fontSize: fontSize + 'px' }"></div>
</template>
<script setup>
const isActive = true
const hasError = false
const textColor = "red"
const fontSize = 16
</script>
布尔属性绑定
对于布尔属性(如 disabled
、checked
),Vue 会根据绑定值的真假来决定是否添加该属性:
vue
xml
<template>
<button :disabled="isDisabled">点击我</button>
<input type="checkbox" :checked="isChecked" />
</template>
<script setup>
const isDisabled = true // 按钮会被禁用
const isChecked = true // 复选框会被选中
</script>
动态属性名
可以使用方括号语法绑定动态的属性名:
vue
<template>
<div :[attributeName]="value"></div>
</template>
<script setup>
const attributeName = "data-id"
const value = 100
</script>
以上代码会渲染为:<div data-id="100"></div>
通过 Attribute 绑定,Vue 实现了数据与视图的响应式关联,当数据发生变化时,对应的属性值也会自动更新。