以下是Vue3模板语法的教程,结合最新官方网页和实战案例整理而成:


一、模板语法概述

Vue3模板语法通过声明式方式将数据与视图绑定,核心功能包括:

  • 数据绑定
  • 指令系统
  • 组件化开发
  • 响应式更新

模板语法最终会被编译为虚拟DOM渲染函数,支持HTML扩展和Vue指令。


二、数据绑定

1. 文本插值

使用{{ }}实现动态文本渲染,支持JavaScript表达式:

<!-- 基础插值 -->
<p>{{ message }}</p>

<!-- 表达式 -->
<p>{{ message.split('').reverse().join('') }}</p>
  • 注意:不能包含语句(如iffor),需用三元表达式替代。

2. 属性绑定

通过v-bind(简写为:)动态绑定属性:

<!-- 绑定图片地址 -->
<img :src="imageURL" alt="Vue Logo">

<!-- 动态类名 -->
<div :class="{ active: isActive }"></div>

3. 原始HTML

使用v-html渲染HTML字符串(需注意XSS风险):

<div v-html="rawHtml"></div>

三、指令系统

1. 条件渲染

  • v-if:惰性渲染,条件为假时移除DOM
  • v-show:通过CSS控制显示,始终保留DOM
<div v-if="isLoggedIn">欢迎回来!</div>
<div v-show="isLoading">加载中...</div>

2. 列表渲染

使用v-for遍历数组/对象,并配合:key优化性能:

<!-- 遍历数组 -->
<ul>
  <li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>

<!-- 遍历对象 -->
<div v-for="(value, key) in obj" :key="key">{{ key }}: {{ value }}</div>

3. 事件绑定

  • 基础事件:@click
  • 事件修饰符:.stop.prevent.once
<!-- 阻止默认行为 -->
<form @submit.prevent="onSubmit"></form>

<!-- 阻止事件冒泡 -->
<a @click.stop="doThis"></a>

4. 双向绑定

v-model实现表单输入与数据同步:

<input v-model="username">
<!-- 组件内使用 -->
<custom-input v-model="value"></custom-input>

四、组件化开发

1. 单文件组件(SFC)

.vue文件包含三大块:

<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue'
const message = ref('Hello Vue3')
</script>

<style scoped>
div { color: blue; }
</style>

2. 父子组件通信

  • Props:父组件向子组件传递数据
<!-- 子组件定义Props -->
<script setup>
defineProps({
  title: String
})
</script>

<!-- 父组件使用 -->
<ChildComponent :title="parentTitle" />
  • 自定义事件:子组件向父组件发送消息
<!-- 子组件触发事件 -->
<button @click="$emit('update')">更新</button>

<!-- 父组件监听事件 -->
<ChildComponent @update="handleUpdate" />

五、实战示例:TodoList

<template>
  <div>
    <input v-model="newTodo" @keyup.enter="addTodo">
    <ul>
      <li v-for="(todo, index) in todos" :key="todo.id">
        <span :class="{ done: todo.done }">{{ todo.text }}</span>
        <button @click="toggleTodo(index)">完成</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const todos = ref([
  { id: 1, text: '学习Vue3', done: false }
])

const addTodo = () => {
  todos.value.push({
    id: Date.now(),
    text: newTodo.value,
    done: false
  })
  newTodo.value = ''
}

const toggleTodo = (index) => {
  todos.value[index].done = !todos.value[index].done
}
</script>

<style>
.done {
  text-decoration: line-through;
}
</style>

六、最佳实践

  1. 单一职责原则:每个组件专注单一功能
  2. 合理使用keyv-for必须绑定唯一key
  3. 避免直接修改Props:通过emit通知父组件
  4. 使用<script setup>:简化Composition API代码

通过以上内容,可快速掌握Vue3模板语法核心。更多高级特性(如计算属性、侦听器、插槽)可参考官方网页。