2.模版语法和指令
下面为你系统性、清晰地介绍 Vue 3 的模板语法(Template Syntax)和常用指令(Directives),并配合示例帮助理解。
✅ 一、Vue 3 模板语法(Template Syntax)
Vue 的模板语法本质是 在 HTML 中绑定数据 的一种声明式方式。核心理念:数据驱动视图。
1. 插值语法(Mustache Syntax)
● 文本插值
<p>{{ message }}</p>
● 支持 JS 表达式
<p>{{ count + 1 }}</p>
<p>{{ user.name.toUpperCase() }}</p>
⚠️ 不支持复杂语句,如 if / for。
2. 属性绑定(v-bind)
● 基础绑定
<img v-bind:src="imageUrl">
● 简写形式 :
<img :src="imageUrl">
● 绑定 class
<div :class="{ active: isActive }"></div>
● 绑定 style
<div :style="{ color: activeColor, fontSize: size + 'px' }"></div>
3. 事件绑定(v-on)
● 基本绑定
<button v-on:click="increment">+</button>
● 简写 @
<button @click="increment">+</button>
● 修饰符
<form @submit.prevent="onSubmit"></form>
4. 条件渲染
● v-if / v-else-if / v-else
<p v-if="age >= 18">成人</p>
<p v-else>未成年</p>
● v-show(仅隐藏,不移除 DOM)
<p v-show="isVisible">显示我</p>
对比:
| 指令 | 是否进入/离开 DOM | 开销 |
|---|---|---|
v-if | 是 | 高 |
v-show | 否(仅 display) | 低 |
5. 列表渲染(v-for)
● 基本用法
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
● 带 index
<li v-for="(item, index) in items" :key="index">
{{ index }} - {{ item }}
</li>
6. 双向绑定(v-model)
● 表单输入绑定
<input v-model="username">
● 绑定 Checkbox
<input type="checkbox" v-model="checked">
● 修饰符
<input v-model.trim="keyword">
<input v-model.number="age">
<input v-model.lazy="msg">
7. 模板中的计算属性与方法
● 计算属性在模板中直接使用
<p>{{ reversedMessage }}</p>
● 方法在事件中使用
<button @click="sayHello">Click</button>
✅ 二、Vue 3 常用指令(Directives)
Vue 的指令是带有 v- 前缀的特殊属性,用于将逻辑绑定到 DOM。
指令总表(Vue 3 常用)
| 指令 | 作用 |
|---|---|
v-text | 设置元素文本内容 |
v-html | 设置 HTML,⚠️ 可能有 XSS 风险 |
v-bind / : | 绑定属性 |
v-on / @ | 绑定事件 |
v-if v-else-if v-else | 条件渲染 |
v-show | 显示/隐藏 |
v-for | 列表渲染 |
v-model | 双向绑定 |
v-slot | 插槽 |
v-pre | 跳过编译 |
v-once | 只渲染一次 |
v-memo(Vue3) | 缓存模板片段 |
v-cloak | 页面加载未编译前隐藏模板 |
各指令详细示例
1. v-text
<p v-text="msg"></p>
等同于
<p>{{ msg }}</p>
2. v-html(渲染 HTML 内容)
<div v-html="htmlContent"></div>
⚠️ 不安全,除非你确定内容可信。
3. v-pre(跳过编译)
<p v-pre>{{ 这段不会被编译 }}</p>
4. v-once(静态内容的优化)
<h1 v-once>{{ title }}</h1>
5. v-slot(插槽)
<card>
<template v-slot:header>
<h1>我是标题</h1>
</template>
</card>
简写为:
<card #header>
<h1>我是标题</h1>
</card>
🔥 三、综合示例(最常见用法)
<div id="app">
<h2>{{ title }}</h2>
<input v-model="inputText" placeholder="输入内容">
<p v-if="inputText.length > 0">
您输入了:{{ inputText }}
</p>
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item }}
</li>
</ul>
<button @click="addItem">添加</button>
</div>
const app = Vue.createApp({
data() {
return {
title: 'Vue3 示例',
inputText: '',
list: ['苹果', '香蕉']
}
},
methods: {
addItem() {
if (this.inputText) {
this.list.push(this.inputText);
this.inputText = '';
}
}
}
})
app.mount('#app')
🎯 总结
Vue 3 模板语法的核心:
{{}}插值:绑定文本内容:绑定属性(v-bind)@绑定事件(v-on)- 条件渲染:
v-if/v-show - 列表渲染:
v-for - 双向绑定:
v-model - 插槽:
v-slot - 其它辅助指令如
v-text、v-html、v-once...
如果你需要的话,我还可以帮你:
📌 整理成 Markdown 文档 📌 附带完整示例 demo(可运行) 📌 给你画一张 Vue 模板语法速查图 📌 继续讲解 Vue3 生命周期、响应式系统、组件等
需要哪个?