Vue 3 核心技术演示平台 - 完整技术文档
Vue 3 核心技术演示平台 - 完整技术文档
📋 目录
- 项目简介
- 技术栈
- 核心特性
- 项目结构
- 技术详解
- 快速开始
- 最佳实践
- 常见问题
🎯 项目简介
这是一个全面展示 Vue 3 核心技术和热点特性的演示平台。项目涵盖了 Vue 3 的所有重要特性,包括 Composition API、响应式系统、生命周期、Teleport、Suspense、自定义指令和组合式函数等。
项目目标
- ✅ 系统学习 Vue 3 核心 API
- ✅ 理解现代前端开发最佳实践
- ✅ 掌握组件化开发思想
- ✅ 提升代码复用能力
🛠️ 技术栈
核心框架
- Vue 3.x - 渐进式 JavaScript 框架
- Vite 5.x - 下一代前端构建工具
开发语言
- JavaScript (ES6+) - 使用最新 ECMAScript 特性
- HTML5 & CSS3 - 现代 Web 标准
包管理
- npm - Node.js 包管理器
✨ 核心特性
1. Composition API (组合式 API)
特点:
- 更好的逻辑复用
- 更灵活的代码组织
- 完美的 TypeScript 支持
- 更好的 Tree-shaking
示例代码:
<script setup>
import { ref, reactive, computed } from 'vue'// 响应式数据
const count = ref(0)
const user = reactive({name: 'Vue Developer',age: 25
})// 计算属性
const doubledCount = computed(() => count.value * 2)// 方法
const increment = () => {count.value++
}
</script>
vs Options API 对比:
| 特性 | Options API | Composition API |
|---|---|---|
| 代码组织 | 按选项类型 | 按逻辑功能 |
| 代码复用 | Mixins | Composables |
| TypeScript | 支持较弱 | 完美支持 |
| Tree-shaking | 较差 | 优秀 |
2. 响应式系统 (Reactivity System)
Vue 3 使用 Proxy 实现响应式,相比 Vue 2 的 Object.defineProperty 有显著优势。
核心 API
ref - 基础类型响应式
import { ref } from 'vue'const count = ref(0)
console.log(count.value) // 0
count.value++ // 触发响应式更新
reactive - 对象响应式
import { reactive } from 'vue'const state = reactive({user: {name: 'Vue',age: 25}
})state.user.name = 'React' // 深层响应式
computed - 计算属性
import { computed } from 'vue'const fullName = computed(() => {return `${firstName.value} ${lastName.value}`
})
watch - 侦听器
import { watch } from 'vue'// 侦听单个源
watch(count, (newVal, oldVal) => {console.log(`从 ${oldVal} 变为 ${newVal}`)
})// 侦听多个源
watch([count, name], ([newCount, newName]) => {console.log('数据变化了')
})// 深度侦听
watch(obj, () => {console.log('对象变化')
}, { deep: true })
watchEffect - 自动依赖追踪
import { watchEffect } from 'vue'watchEffect(() => {console.log(`Count is ${count.value}`)// 自动追踪 count 的变化
})
响应式工具函数
toRef- 为响应式对象的单个属性创建 reftoRefs- 将响应式对象转换为普通对象,每个属性都是 refunref- 返回 ref 的值或原始值isRef- 检查值是否为 refisReactive- 检查对象是否为 reactive 创建的readonly- 创建只读代理
3. 生命周期钩子 (Lifecycle Hooks)
Vue 3 在 Composition API 中引入了新的生命周期钩子。
钩子对照表
| Options API | Composition API | 说明 |
|---|---|---|
| beforeCreate | setup() | 组件实例创建前 |
| created | setup() | 组件实例创建后 |
| beforeMount | onBeforeMount | 组件挂载前 |
| mounted | onMounted | 组件挂载后 |
| beforeUpdate | onBeforeUpdate | 数据更新前 |
| updated | onUpdated | 数据更新后 |
| beforeUnmount | onBeforeUnmount | 组件卸载前 |
| unmounted | onUnmounted | 组件卸载后 |
| errorCaptured | onErrorCaptured | 捕获子组件错误 |
使用示例
import { onMounted, onUnmounted } from 'vue'export default {setup() {onMounted(() => {console.log('组件已挂载')// 初始化操作:API调用、DOM操作等})onUnmounted(() => {console.log('组件即将卸载')// 清理操作:清除定时器、取消请求等})}
}
常见应用场景
onMounted
- 发起 API 请求
- 初始化第三方库
- DOM 操作
- 启动定时器
onUnmounted
- 清除定时器
- 取消网络请求
- 移除事件监听
- 清理副作用
onUpdated
- DOM 更新后的操作
- 滚动位置调整
- 动画触发
4. Teleport (传送门)
Teleport 允许我们将组件的 HTML 渲染到 DOM 中的任意位置。
使用场景
- 模态框 (Modal)
- 通知 (Notifications)
- 抽屉 (Drawer)
- 工具提示 (Tooltip)
基础用法
<template><!-- 将模态框传送到 body --><teleport to="body"><div v-if="showModal" class="modal"><h3>模态框</h3><p>内容</p><button @click="showModal = false">关闭</button></div></teleport>
</template><script setup>
import { ref } from 'vue'
const showModal = ref(false)
</script>
优势
- ✅ 避免 z-index 冲突
- ✅ 解决 overflow 限制
- ✅ 保持组件逻辑不变
- ✅ 更好的可访问性
5. Suspense (异步组件)
Suspense 用于优雅地处理异步组件的加载状态。
基础用法
<template><Suspense><!-- 默认内容:异步组件 --><template #default><AsyncComponent /></template><!-- 后备内容:加载中显示 --><template #fallback><div class="loading">加载中...</div></template></Suspense>
</template><script setup>
import { defineAsyncComponent } from 'vue'const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue')
)
</script>
配合 async setup
<script setup>
const data = await fetchData()
// 组件会等待数据加载完成
</script>
注意事项
⚠️ Suspense 目前仍是实验性特性,API 可能会变化
6. 自定义指令 (Custom Directives)
自定义指令用于封装可复用的 DOM 操作逻辑。
指令钩子
const myDirective = {// 在绑定元素的 attribute 前调用created(el, binding, vnode, prevVnode) {},// 在元素被插入到 DOM 前调用beforeMount(el, binding, vnode, prevVnode) {},// 在绑定元素的父组件及所有子节点都挂载完成后调用mounted(el, binding, vnode, prevVnode) {},// 绑定元素的父组件更新前调用beforeUpdate(el, binding, vnode, prevVnode) {},// 在绑定元素的父组件及所有子节点都更新后调用updated(el, binding, vnode, prevVnode) {},// 绑定元素的父组件卸载前调用beforeUnmount(el, binding, vnode, prevVnode) {},// 绑定元素的父组件卸载后调用unmounted(el, binding, vnode, prevVnode) {}
}
实用指令示例
v-focus - 自动聚焦
app.directive('focus', {mounted(el) {el.focus()}
})
v-loading - 加载状态
app.directive('loading', {mounted(el, binding) {if (binding.value) {// 显示加载动画}},updated(el, binding) {// 根据值更新状态}
})
v-lazy - 图片懒加载
app.directive('lazy', {mounted(el, binding) {const observer = new IntersectionObserver((entries) => {if (entries[0].isIntersecting) {el.src = binding.valueobserver.unobserve(el)}})observer.observe(el)}
})
v-clickoutside - 点击外部
app.directive('clickoutside', {mounted(el, binding) {el._clickOutside = (event) => {if (!el.contains(event.target)) {binding.value()}}document.addEventListener('click', el._clickOutside)},unmounted(el) {document.removeEventListener('click', el._clickOutside)}
})
7. 组合式函数 (Composables)
Composables 是 Vue 3 中实现逻辑复用的最佳方式。
命名规范
- 使用
use前缀 - 驼峰命名法
- 例如:
useMouse,useCounter,useFetch
示例:useMouse
// composables/useMouse.js
import { ref, onMounted, onUnmounted } from 'vue'export function useMouse() {const x = ref(0)const y = ref(0)function update(event) {x.value = event.pageXy.value = event.pageY}onMounted(() => {window.addEventListener('mousemove', update)})onUnmounted(() => {window.removeEventListener('mousemove', update)})return { x, y }
}
在组件中使用
<script setup>
import { useMouse } from './composables/useMouse'const { x, y } = useMouse()
</script><template><div>鼠标位置: {{ x }}, {{ y }}</div>
</template>
更多实用 Composables
useCounter - 计数器
export function useCounter(initialValue = 0) {const count = ref(initialValue)const increment = () => count.value++const decrement = () => count.value--const reset = () => count.value = initialValuereturn { count, increment, decrement, reset }
}
useLocalStorage - 本地存储
export function useLocalStorage(key, defaultValue) {const value = ref(localStorage.getItem(key) || defaultValue)watch(value, (newValue) => {localStorage.setItem(key, newValue)})return value
}
useFetch - 数据获取
export function useFetch(url) {const data = ref(null)const loading = ref(false)const error = ref(null)const execute = async () => {loading.value = truetry {const response = await fetch(url)data.value = await response.json()} catch (e) {error.value = e} finally {loading.value = false}}return { data, loading, error, execute }
}
优势
- 📦 代码复用 - 在多个组件间共享逻辑
- 🎯 关注点分离 - 按功能组织代码
- 🔍 类型推导 - 完美支持 TypeScript
- 🧩 灵活组合 - 可以自由组合多个 composables
- 🧪 易于测试 - 独立函数更容易测试
8. Provide / Inject (依赖注入)
Provide 和 Inject 提供了跨层级组件通信的方式。
基础用法
父组件提供
<script setup>
import { provide, ref } from 'vue'const theme = ref('light')
provide('theme', theme)
</script>
子组件注入
<script setup>
import { inject } from 'vue'const theme = inject('theme')
// 提供默认值
const config = inject('config', { apiUrl: 'default' })
</script>
使用 Symbol
// keys.js
export const ThemeKey = Symbol('theme')// 父组件
import { ThemeKey } from './keys'
provide(ThemeKey, theme)// 子组件
import { ThemeKey } from './keys'
const theme = inject(ThemeKey)
适用场景
- ✅ 主题配置
- ✅ 语言设置
- ✅ 用户信息
- ✅ 全局配置
注意事项
- ⚠️ 避免过度使用
- ⚠️ 使用 Symbol 避免命名冲突
- ⚠️ 提供响应式数据时使用 ref/reactive
📁 项目结构
pythonDemo/
├── src/
│ ├── components/ # 组件目录
│ │ ├── CompositionAPIDemo.vue # Composition API 演示
│ │ ├── ReactivityDemo.vue # 响应式系统演示
│ │ ├── LifecycleDemo.vue # 生命周期演示
│ │ ├── TeleportDemo.vue # Teleport 演示
│ │ ├── SuspenseDemo.vue # Suspense 演示
│ │ ├── DirectivesDemo.vue # 自定义指令演示
│ │ ├── ComposablesDemo.vue # Composables 演示
│ │ └── ProvideInjectDemo.vue # Provide/Inject 演示
│ ├── composables/ # 组合式函数
│ │ └── index.js # 所有 composables
│ ├── App.vue # 主应用组件
│ └── main.js # 应用入口
├── index.html # HTML 入口
├── package.json # 依赖配置
├── vite.config.js # Vite 配置
└── Vue3核心技术文档.md # 本文档
演示代码地址
🚀 快速开始
环境要求
- Node.js >= 16.0
- npm >= 7.0
安装依赖
npm install
启动开发服务器
npm run dev
访问 http://localhost:5173 查看演示
构建生产版本
npm run build
预览生产版本
npm run preview
💡 最佳实践
1. 优先使用 Composition API
// ✅ 推荐
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>// ❌ 不推荐(除非有特殊需求)
export default {data() {return { count: 0 }}
}
2. 合理使用 ref 和 reactive
// ✅ 基础类型用 ref
const count = ref(0)
const name = ref('Vue')// ✅ 对象用 reactive
const state = reactive({user: { name: 'Vue', age: 25 },settings: { theme: 'light' }
})// ❌ 避免混用导致混乱
const badExample = reactive({count: ref(0) // 不推荐
})
3. 提取可复用逻辑为 Composables
// ✅ 好的做法
// composables/useAuth.js
export function useAuth() {const user = ref(null)const login = async () => { /* ... */ }const logout = () => { /* ... */ }return { user, login, logout }
}// 在组件中使用
const { user, login, logout } = useAuth()
4. 使用 TypeScript
// ✅ 类型安全
interface User {name: stringage: number
}const user = ref<User>({name: 'Vue',age: 25
})
5. 正确清理副作用
// ✅ 好的做法
onMounted(() => {const timer = setInterval(() => {// ...}, 1000)onUnmounted(() => {clearInterval(timer)})
})// ❌ 忘记清理
onMounted(() => {setInterval(() => {// 内存泄漏!}, 1000)
})
6. 避免在 computed 中产生副作用
// ❌ 不推荐
const badComputed = computed(() => {count.value++ // 副作用!return count.value * 2
})// ✅ 推荐
const goodComputed = computed(() => {return count.value * 2
})
7. 合理使用 watch
// ✅ 明确的依赖
watch(count, (newVal) => {console.log(newVal)
})// ✅ 自动追踪依赖
watchEffect(() => {console.log(count.value)
})// ⚠️ 注意性能
watch(largeObject, () => {// 深度侦听可能影响性能
}, { deep: true })
❓ 常见问题
Q1: ref 和 reactive 的区别?
A:
ref用于基础类型,需要.value访问reactive用于对象,直接访问属性ref可以包装任何类型,reactive只能用于对象
Q2: 什么时候使用 Composables?
A: 当你有可复用的有状态逻辑时:
- 跨组件共享的功能
- 复杂的业务逻辑
- 与外部系统交互
Q3: Provide/Inject vs Props?
A:
- Props 适合父子组件直接通信
- Provide/Inject 适合深层嵌套组件通信
- Props 数据流更明确,Provide/Inject 更隐式
Q4: 如何优化性能?
A:
- 使用
v-once渲染静态内容 - 使用
v-memo缓存子树 - 使用
shallowRef和shallowReactive - 合理拆分组件
- 使用异步组件和代码分割
Q5: 生命周期钩子执行顺序?
A:
- setup()
- onBeforeMount
- onMounted
- onBeforeUpdate (数据变化时)
- onUpdated (数据变化后)
- onBeforeUnmount (卸载前)
- onUnmounted (卸载后)
📚 学习资源
官方文档
- Vue 3 官方文档
- Vite 官方文档
推荐阅读
- Vue 3 Composition API 深入理解
- Vue 3 响应式原理
- Vue 3 性能优化指南
社区资源
- Vue.js 中文社区
- Awesome Vue 3
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📄 许可证
MIT License
🎉 总结
本项目全面展示了 Vue 3 的核心技术和最佳实践:
- ✅ Composition API - 更好的逻辑复用
- ✅ 响应式系统 - 基于 Proxy 的强大响应式
- ✅ 生命周期 - 灵活的组件生命周期管理
- ✅ Teleport - 突破 DOM 层级限制
- ✅ Suspense - 优雅的异步处理
- ✅ 自定义指令 - 可复用的 DOM 操作
- ✅ Composables - 逻辑复用的最佳实践
- ✅ Provide/Inject - 跨层级组件通信
通过学习和实践这些技术,你将能够构建更加优雅、高效、可维护的 Vue 3 应用。
最后更新时间: 2025-10-24
项目版本: 1.0.0
Vue 版本: 3.x
Vite 版本: 5.x
