vue3 attribute绑定

在 Vue3 中,Attribute 绑定是一个核心概念,用于将组件的数据动态绑定到 HTML 元素的属性上。最常用的方式是使用 v-bind 指令,也可以使用简写形式 :

基本用法

  1. 完整语法 (v-bind)

vue

xml 复制代码
<template>
  <img v-bind:src="imageUrl" />
</template>

<script setup>
const imageUrl = "https://picsum.photos/200/300"
</script>
  1. 简写语法 (:)

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 对 classstyle 有特殊处理,可以使用对象或数组语法:

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>

布尔属性绑定

对于布尔属性(如 disabledchecked),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 实现了数据与视图的响应式关联,当数据发生变化时,对应的属性值也会自动更新。

相关推荐
San813_LDD20 分钟前
[C语言]《Dev-C++ 报错解决手册(Day0607 精华版)》
java·前端·javascript
xiaofeichaichai6 小时前
Webpack
前端·webpack·node.js
问心无愧05137 小时前
ctf show web入门111
android·前端·笔记
唐某人丶7 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界7 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌7 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel8 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3119 小时前
https连接传输流程
前端·面试
徐小夕9 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github