Vue3 模板语法详解
概述
Vue3 的模板语法让你可以在 HTML 中直接使用 Vue 的功能。模板会被编译成渲染函数,最终生成真实的 DOM。
模板编译流程
常用指令
1. 条件渲染
v-if/v-else/v-else-if
根据条件显示或隐藏元素。
<template>
<div>
<h1 v-if="status === 'success'">操作成功!</h1>
<h1 v-else-if="status === 'error'">操作失败!</h1>
<h1 v-else>处理中...</h1>
</div>
</template>
<script>
export default {
setup() {
const status = ref("success");
return { status };
},
};
</script>
v-show
通过 CSS 的 display 属性控制显示隐藏。
<template>
<div>
<p v-show="isVisible">这个段落会根据 isVisible 的值显示或隐藏</p>
</div>
</template>
<script>
export default {
setup() {
const isVisible = ref(true);
return { isVisible };
},
};
</script>
v-if vs v-show 的区别:
v-if是真正的条件渲染,会销毁和重建元素v-show只是切换 CSS 的 display 属性v-if适合不经常切换的场景,v-show适合频繁切换的场景
2. 列表渲染
v-for
循环渲染数组或对象。
<template>
<div>
<!-- 渲染数组 -->
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }}. {{ item.name }}
</li>
</ul>
<!-- 渲染对象 -->
<div v-for="(value, key) in userInfo" :key="key">
{{ key }}: {{ value }}
</div>
<!-- 渲染数字范围 -->
<span v-for="n in 5" :key="n">{{ n }}</span>
</div>
</template>
<script>
export default {
setup() {
const items = ref([
{ id: 1, name: "苹果" },
{ id: 2, name: "香蕉" },
{ id: 3, name: "橙子" },
]);
const userInfo = ref({
name: "张三",
age: 25,
city: "北京",
});
return { items, userInfo };
},
};
</script>
注意事项:
- 始终为
v-for提供:key属性 key应该是唯一的,通常使用数据的 id 或索引- 避免使用对象作为 key
3. 属性绑定
v-bind (简写为 😃
动态绑定属性。
<template>
<div>
<!-- 绑定 class -->
<div :class="{ active: isActive, 'text-danger': hasError }">动态类名</div>
<!-- 绑定 style -->
<div :style="{ color: textColor, fontSize: fontSize + 'px' }">动态样式</div>
<!-- 绑定其他属性 -->
<img :src="imageSrc" :alt="imageAlt" />
<a :href="linkUrl" :target="linkTarget">链接</a>
</div>
</template>
<script>
export default {
setup() {
const isActive = ref(true);
const hasError = ref(false);
const textColor = ref("red");
const fontSize = ref(16);
const imageSrc = ref("/images/logo.png");
const imageAlt = ref("Logo");
const linkUrl = ref("https://vuejs.org");
const linkTarget = ref("_blank");
return {
isActive,
hasError,
textColor,
fontSize,
imageSrc,
imageAlt,
linkUrl,
linkTarget,
};
},
};
</script>
4. 事件绑定
v-on (简写为 @)
绑定事件处理器。
<template>
<div>
<!-- 基本事件绑定 -->
<button @click="handleClick">点击我</button>
<!-- 传递参数 -->
<button @click="handleClickWithParam('hello')">传递参数</button>
<!-- 获取事件对象 -->
<button @click="handleClickWithEvent">获取事件对象</button>
<!-- 事件修饰符 -->
<form @submit.prevent="handleSubmit">
<input @keyup.enter="handleEnter" />
</form>
<!-- 多个修饰符 -->
<button @click.stop.prevent="handleClick">阻止默认行为和冒泡</button>
</div>
</template>
<script>
export default {
setup() {
const handleClick = () => {
console.log("按钮被点击了");
};
const handleClickWithParam = (message) => {
console.log("收到消息:", message);
};
const handleClickWithEvent = (event) => {
console.log("事件对象:", event);
};
const handleSubmit = () => {
console.log("表单提交");
};
const handleEnter = () => {
console.log("按下了回车键");
};
return {
handleClick,
handleClickWithParam,
handleClickWithEvent,
handleSubmit,
handleEnter,
};
},
};
</script>
常用事件修饰符:
.prevent- 阻止默认行为.stop- 阻止事件冒泡.capture- 使用事件捕获模式.self- 只在事件目标上触发.once- 只触发一次.passive- 不阻止默认行为
5. 双向数据绑定
v-model
实现表单输入和数据的双向绑定。
<template>
<div>
<!-- 文本输入 -->
<input v-model="message" placeholder="请输入消息" />
<p>输入的消息: {{ message }}</p>
<!-- 多行文本 -->
<textarea v-model="description" placeholder="请输入描述"></textarea>
<p>描述: {{ description }}</p>
<!-- 复选框 -->
<input type="checkbox" v-model="isChecked" />
<label>是否选中: {{ isChecked }}</label>
<!-- 单选按钮 -->
<input type="radio" v-model="gender" value="male" />
<label>男</label>
<input type="radio" v-model="gender" value="female" />
<label>女</label>
<p>选择的性别: {{ gender }}</p>
<!-- 选择框 -->
<select v-model="selectedCity">
<option value="">请选择城市</option>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="guangzhou">广州</option>
</select>
<p>选择的城市: {{ selectedCity }}</p>
</div>
</template>
<script>
export default {
setup() {
const message = ref("");
const description = ref("");
const isChecked = ref(false);
const gender = ref("");
const selectedCity = ref("");
return {
message,
description,
isChecked,
gender,
selectedCity,
};
},
};
</script>
自定义组件的 v-model
<!-- 父组件 -->
<template>
<div>
<CustomInput v-model="searchText" />
<p>搜索文本: {{ searchText }}</p>
</div>
</template>
<script>
import CustomInput from "./CustomInput.vue";
export default {
components: { CustomInput },
setup() {
const searchText = ref("");
return { searchText };
},
};
</script>
<!-- 子组件 CustomInput.vue -->
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
placeholder="请输入搜索内容"
/>
</template>
<script>
export default {
props: {
modelValue: {
type: String,
default: "",
},
},
emits: ["update:modelValue"],
};
</script>
模板语法最佳实践
1. 保持模板简洁
<!-- ❌ 不推荐:模板中放置复杂逻辑 -->
<div
v-if="user && user.profile && user.profile.address && user.profile.address.city === 'Beijing'"
>
北京用户
</div>
<!-- ✅ 推荐:将复杂逻辑提取到计算属性 -->
<div v-if="isBeijingUser">北京用户</div>
2. 合理使用 key
<!-- ❌ 不推荐:使用索引作为 key -->
<li v-for="(item, index) in items" :key="index">{{ item.name }}</li>
<!-- ✅ 推荐:使用唯一标识作为 key -->
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
3. 避免在模板中使用复杂表达式
<!-- ❌ 不推荐:模板中放置复杂计算 -->
<p>{{ user.firstName + ' ' + user.lastName + ' (' + user.age + '岁)' }}</p>
<!-- ✅ 推荐:使用计算属性 -->
<p>{{ fullNameWithAge }}</p>
总结
Vue3 的模板语法提供了强大而灵活的声明式渲染能力。通过合理使用各种指令和语法特性,你可以构建出清晰、易维护的 Vue 应用。记住保持模板的简洁性,将复杂的逻辑提取到 JavaScript 代码中。
