Skip to content
第 2 章 前端 ⏱ 12 分钟阅读

第 2 章:模板语法 ​

学习目标 ​

  • 掌握插值、指令、事件绑定的写法
  • 理解 v-if / v-show / v-for 的差异
  • 用 v-model 双向绑定表单
  • 避开渲染和绑定的 4 个坑

一、文本插值 ​

vue
<script setup lang="ts">
const name = ref('Vue');
const html = ref('<b>粗体</b>');
</script>

<template>
	<p>{{ name }}</p>
	<!-- 转义输出:Vue -->
	<p v-text="name"></p>
	<!-- 等价于 {{ }} -->
	<p v-html="html"></p>
	<!-- ⚠️ 原始 HTML,XSS 风险 -->
</template>

⚠️ 坑 1:v-html 不要拼用户输入,否则会被注入 <script>。

二、属性绑定 ​

vue
<script setup lang="ts">
const url = 'https://vuejs.org';
const isDisabled = ref(true);
</script>

<template>
	<a :href="url">官网</a>
	<button :disabled="isDisabled">按钮</button>
	<img :src="`/img/${name}.png`" />
	<!-- 字符串模板拼接 -->
</template>

:href 是 v-bind:href 的简写,Vue 3 推荐只写 :。

三、条件渲染 ​

vue
<template>
	<p v-if="score >= 90">优秀</p>
	<p v-else-if="score >= 60">及格</p>
	<p v-else>不及格</p>

	<p v-show="ok">v-show 用 display:none 切换</p>
</template>
指令机制适用场景
v-if真正卸载 DOM条件很少变化
v-show切换 display频繁切换

⚠️ 坑 2:v-if 挂在 <template> 上时,用 v-else 时,必须连写。

四、列表渲染 ​

vue
<script setup lang="ts">
const list = [
	{ id: 1, name: 'Alice' },
	{ id: 2, name: 'Bob' },
];
</script>

<template>
	<ul>
		<li v-for="item in list" :key="item.id">
			{{ item.name }}
		</li>
	</ul>
</template>

⚠️ 坑 3::key 必须用唯一稳定的 id,不要用 index,否则增删会重渲染整个列表。

vue
<!-- v-for + v-if 不要写在同一元素 -->
<li v-for="u in users" v-if="u.active" :key="u.id">  ❌
<!-- 套一层 template -->
<template v-for="u in users" :key="u.id">
  <li v-if="u.active">{{ u.name }}</li>
</template>

⚠️ 坑 4:Vue 3 中 v-if 比 v-for 优先级高,同元素时 v-if 没法访问 v-for 变量。

五、事件绑定 ​

vue
<script setup lang="ts">
const count = ref(0);
const handle = (n: number, e: MouseEvent) => {
	console.log(n, e.target);
};
</script>

<template>
	<button @click="count++">+1</button>
	<button @click="handle(5, $event)">传参</button>
	<input @keyup.enter="submit" />
	<!-- 按键修饰符 -->
	<button @click.stop="save">阻止冒泡</button>
</template>

常用修饰符:.stop .prevent .once .self .enter .esc .ctrl。

六、双向绑定 v-model ​

vue
<script setup lang="ts">
const text = ref('');
const checked = ref(false);
const city = ref('sh');
</script>

<template>
	<input v-model="text" />
	<input type="checkbox" v-model="checked" />
	<select v-model="city">
		<option value="bj">北京</option>
		<option value="sh">上海</option>
	</select>
</template>

v-model 本质是 :value + @input 的语法糖。

七、本章小结 ​

语法作用
&#123;&#123; &#125;&#125;文本插值
v-bind / :属性绑定
v-if / v-show条件渲染
v-for列表渲染,务必带 :key
v-on / @事件绑定
v-model表单双向绑定

动手练习 ​

  1. 待办列表:用 v-for 渲染 3 条 todo,带 checkbox
  2. 搜索过滤:输入框 v-model 绑 keyword,列表用 v-for 实时过滤
  3. 键盘事件:输入框按 Enter 触发 alert,按 Esc 清空

下一章:第 3 章:响应式 ref / reactive →

本站基于 VitePress 构建 · 由 StackHub 团队维护