第 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 的语法糖。
七、本章小结
| 语法 | 作用 |
|---|---|
{{ }} | 文本插值 |
v-bind / : | 属性绑定 |
v-if / v-show | 条件渲染 |
v-for | 列表渲染,务必带 :key |
v-on / @ | 事件绑定 |
v-model | 表单双向绑定 |
动手练习
- 待办列表:用
v-for渲染 3 条 todo,带 checkbox - 搜索过滤:输入框
v-model绑keyword,列表用v-for实时过滤 - 键盘事件:输入框按 Enter 触发 alert,按 Esc 清空
下一章:第 3 章:响应式 ref / reactive →