模板语法
插值、指令 v-if/v-for/v-bind。
模板语法
这一课你将能做到
- 使用插值、
v-bind、v-if/v-show、v-for、v-on写出可运行界面 - 解释
:attr与@event缩写,并正确写v-for的key - 对照 JSX:条件与列表在 Vue 里更常写在模板指令中
为什么要学
模板是 Vue 的「界面说明书」。指令(v-)把常见 DOM 操作收成声明:要不要显示、怎么循环、绑定哪个属性。
与 React 的 {cond && <X/>} / map 同目的,不同语法。
先建立图像
{{ msg }} 文本插值
:title="x" 绑定属性(v-bind)
@click="fn" 绑定事件(v-on)
v-if / v-for 条件与列表
| 指令 | 人话 | 注意 |
|---|---|---|
| v-if | 条件为假时可不渲染 | 切换成本高时考虑 v-show |
| v-show | 用 CSS 显隐 | 仍在 DOM |
| v-for | 列表渲染 | 必配 key |
| v-bind | 动态属性 | 缩写 : |
| v-on | 事件 | 缩写 @ |
跟着做
步骤 1:插值与绑定
<script setup>
import { ref } from "vue";
const msg = ref("入门精讲");
const imageAlt = ref("示意图");
</script>
<template>
<h1>{{ msg }}</h1>
<img :alt="imageAlt" src="/favicon.ico" width="32" height="32" />
</template>
改 msg.value(可再加按钮)应看到标题变。alt 必须用绑定才能吃变量。
步骤 2:条件
<script setup>
import { ref } from "vue";
const published = ref(true);
</script>
<template>
<p v-if="published">已发布</p>
<p v-else>草稿</p>
<button type="button" @click="published = !published">切换</button>
</template>
模板里对 ref 赋值会自动处理;观察 DOM:v-if 切换时节点出现/消失。
步骤 3:列表
<script setup>
import { ref } from "vue";
const lessons = ref([
{ id: 1, title: "模板语法" },
{ id: 2, title: "响应式基础" },
]);
</script>
<template>
<ul>
<li v-for="item in lessons" :key="item.id">{{ item.title }}</li>
</ul>
</template>
:key 用稳定 id,不要用 index(列表会重排/插入时易出诡异复用)。