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

相关推荐
wyzqhhhh3 小时前
less和sass
前端·less·sass
Nan_Shu_6144 小时前
学习:uniapp全栈微信小程序vue3后台-额外/精彩报错篇
前端·学习·微信小程序·小程序·uni-app·notepad++
excel5 小时前
Vue3 中的双向链表依赖管理详解与示例
前端
前端小白从0开始6 小时前
Chrome DevTools高级用法:性能面板内存泄漏排查
前端·chrome·chrome devtools
EveryPossible6 小时前
带有渐变光晕
前端·javascript·css
jojo是只猫6 小时前
Vue 3 开发的 HLS 视频流播放组件+异常处理
前端·javascript·vue.js
卓码软件测评6 小时前
第三方软件登记测试机构:【软件登记测试机构HTML5测试技术】
前端·功能测试·测试工具·html·测试用例·html5
CS Beginner6 小时前
【html】canvas实现一个时钟
前端·html
林烈涛7 小时前
js判断变量是数组还是对象
开发语言·前端·javascript
Komorebi_99997 小时前
Unocss
开发语言·前端