基础知识
Vue 3 核心概念
Vue.js 是一套用于构建用户界面的渐进式框架。Vue 3 引入了 Composition API,提供了更灵活的逻辑复用方式。
Composition API
Composition API 是一组 API,允许我们使用导入的函数而不是声明选项来编写 Vue 组件。它是 Vue 3 的核心特性。
- setup 函数:Composition API 的入口点
- ref 和 reactive:创建响应式数据
- computed 和 watch:计算属性和侦听器
响应式原理
Vue 3 使用 Proxy 对象实现响应式系统,相比 Vue 2 的 Object.defineProperty,Proxy 可以监听更多操作,性能更好。
指令
- v-if:条件渲染,切换时组件会被销毁和重建
- v-show:通过 CSS display 属性切换显示
- v-for:列表渲染
- v-model:双向数据绑定
Vue Router
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页应用。支持嵌套路由、动态路由匹配、导航守卫等功能。
Pinia
Pinia 是 Vue 的官方状态管理库,替代 Vuex。它提供更简单的 API、更好的 TypeScript 支持,是 Vue 3 项目的推荐选择。
图文教程
步骤一:setup 函数
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() {
count.value++;
}
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
<button @click="increment">+1</button>
</div>
</template>
步骤二:ref 与 reactive
import { ref, reactive } from 'vue';
// ref 用于基本类型
const count = ref(0);
console.log(count.value); // 0
// reactive 用于对象
const state = reactive({
name: 'Vue',
version: 3
});
console.log(state.name); // Vue
// 更新数据
function update() {
count.value++;
state.version = 3.2;
}
步骤三:computed 与 watch
import { ref, computed, watch } from 'vue';
const firstName = ref('John');
const lastName = ref('Doe');
// 计算属性
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`;
});
// 侦听器
watch(firstName, (newVal, oldVal) => {
console.log(`Name changed from ${oldVal} to ${newVal}`);
});
// 侦听多个源
watch([firstName, lastName], ([newF, newL]) => {
console.log(`Full name: ${newF} ${newL}`);
});
代码实操
阅读以下代码,理解实现原理,然后尝试修改并运行
实践任务:Vue 3 Composition API 计数器
<script setup>
import { ref, computed, watch } from 'vue';
const count = ref(0);
const step = ref(1);
const double = computed(() => count.value * 2);
const isEven = computed(() => count.value % 2 === 0);
function increment() {
count.value += step.value;
}
function decrement() {
count.value -= step.value;
}
watch(count, (newVal) => {
console.log(`Count changed to: ${newVal}`);
});
</script>
<template>
<div class="counter">
<h2>计数器</h2>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
<p>{{ isEven ? '偶数' : '奇数' }}</p>
<input v-model.number="step" type="number" />
<button @click="decrement">-</button>
<button @click="increment">+</button>
</div>
</template>
练习任务
- 添加重置按钮,将 count 重置为 0
- 添加历史记录功能,记录每次变化的值
- 使用 localStorage 持久化计数器状态