3 - Attribute
绑定cn.vuejs.orgcn.vuejs.org/tutorial
v-bind
在 Vue 中,mustache 语法 (即双大括号) 只能用于文本插值。为了给 attribute 绑定一个动态值,需要使用 v-bind 指令:
<div v-bind:id="dynamicId"></div>简写语法
<div :id="dynamicId"></div>Example 1
<script setup>
import { ref } from 'vue'
const titleClass = ref('title')
</script>
<template>
<h1 :class="titleClass">Make me red</h1> <!-- 此处添加一个动态 class 绑定 -->
</template>
<style>
.title {
color: red;
}
</style>Example 2
🔁 页面运行流程总结
- Vue 应用初始化,sectionId = 'about-section'
- 模板渲染:
- 生成 <a href="#about-section">跳转到 About 区域</a>
- 页面下方生成 <div id="about-section">,并显示“关于我们”内容
- 页面中间有个 500px 空白,用于制造滚动空间
- 用户点击“跳转到 About 区域”按钮
- 浏览器原生锚点功能触发 → 页面自动滚动到 id=“about-section” 的位置
- 用户看到“关于我们”的内容被滚动到视口可见范围
✅ 常见用法举例
| 用法 | 示例 | 说明 |
|---|---|---|
:href | <a :href="link"> | 动态链接地址 |
:src | <img :src="imageUrl"> | 动态图片地址 |
:class | <div :class="activeClass"> | 动态 class 名 |
:style | <div :style="{ color: textColor }"> | 动态内联样式 |
:id | <div :id="sectionId"> | 动态 id(例如锚点跳转) |
:disabled | <button :disabled="isDisabled"> | 控制按钮是否可用 |