Vue3组合式API进阶深入理解和高效使用Composition API前言大家好我是前端老炮儿今天咱们来聊聊Vue3组合式API的进阶用法。你以为ref和reactive就够了那你可太天真了Vue3的Composition API远比你想象的更强大。为什么需要Composition APIOptions API的问题Options API → 逻辑分散 → 难以复用 Options API → 关注点分离 → 阅读困难 Options API → 类型推断差 → 开发体验不佳Composition API的优势逻辑复用变得简单代码组织更加灵活更好的TypeScript支持更细粒度的响应式控制基础API回顾ref和reactivescript setup import { ref, reactive } from vue // ref用于基本类型 const count ref(0) const name ref() // reactive用于对象 const state reactive({ user: { name: 张三, age: 25 }, items: [] }) // 修改ref值 count.value // 修改reactive值 state.user.name 李四 /scriptcomputedscript setup import { ref, computed } from vue const firstName ref(张) const lastName ref(三) // 计算属性 const fullName computed(() { return ${firstName.value}${lastName.value} }) // 可写的计算属性 const fullName2 computed({ get: () ${firstName.value}${lastName.value}, set: (newValue) { const [first, last] newValue.split() firstName.value first lastName.value last } }) /scriptwatch和watchEffectscript setup import { ref, watch, watchEffect } from vue const count ref(0) const name ref() // watch监听特定数据源 watch(count, (newVal, oldVal) { console.log(count changed from ${oldVal} to ${newVal}) }) // 监听多个数据源 watch([count, name], ([newCount, newName], [oldCount, oldName]) { console.log(count: ${oldCount} - ${newCount}) console.log(name: ${oldName} - ${newName}) }) // 深度监听 const state reactive({ user: { name: 张三 } }) watch(state, (newState) { console.log(state changed:, newState) }, { deep: true }) // watchEffect自动追踪依赖 watchEffect(() { console.log(count is: ${count.value}) }) /script进阶APIref进阶script setup import { ref, shallowRef, triggerRef } from vue // shallowRef只追踪顶层值变化 const shallow shallowRef({ name: 张三 }) // 修改嵌套属性不会触发更新 shallow.value.name 李四 // 不会触发更新 // 需要手动触发 triggerRef(shallow) // 触发更新 // ref的特性 const count ref(0) // 获取原始值 console.log(count.value) // 解包 const state reactive({ count }) console.log(state.count) // 自动解包输出0 /scriptreactive进阶script setup import { reactive, shallowReactive, readonly, shallowReadonly } from vue // shallowReactive只响应顶层属性 const shallowState shallowReactive({ user: { name: 张三 } }) // 修改顶层属性会触发更新 shallowState.user { name: 李四 } // 会触发更新 // 修改嵌套属性不会触发更新 shallowState.user.name 王五 // 不会触发更新 // readonly创建只读代理 const state reactive({ count: 0 }) const readOnlyState readonly(state) // 尝试修改会警告 readOnlyState.count // 警告不能修改只读属性 // shallowReadonly只保护顶层 const shallowRead shallowReadonly({ user: { name: 张三 } }) // 顶层不能修改 shallowRead.user {} // 警告 // 嵌套属性可以修改 shallowRead.user.name 李四 // 不会警告 /scriptcomputed进阶script setup import { ref, computed } from vue const items ref([1, 2, 3, 4, 5]) // 计算属性缓存 const doubled computed(() { console.log(computing...) return items.value.map(item item * 2) }) // 只有依赖变化时才重新计算 console.log(doubled.value) // 输出: computing... [2,4,6,8,10] console.log(doubled.value) // 输出: [2,4,6,8,10] (没有重新计算) // 计算属性作为依赖 const sum computed(() { return doubled.value.reduce((acc, val) acc val, 0) }) console.log(sum.value) // 30 /scriptwatch进阶script setup import { ref, watch, watchEffect } from vue const count ref(0) // 立即执行 watch(count, (newVal) { console.log(count:, newVal) }, { immediate: true }) // 深度监听 const state reactive({ nested: { value: 0 } }) watch(state, (newState) { console.log(nested value:, newState.nested.value) }, { deep: true }) // 停止监听 const stop watch(count, (newVal) { console.log(count changed:, newVal) }) // 停止监听 stop() // watchEffect清理 watchEffect((onCleanup) { const timer setTimeout(() { console.log(done) }, 1000) // 清理函数 onCleanup(() { clearTimeout(timer) }) }) /script组合式函数创建组合式函数script setup import { ref, onMounted, onUnmounted } from vue // useMouse组合式函数 function useMouse() { const x ref(0) const y ref(0) function handleMouseMove(e) { x.value e.clientX y.value e.clientY } onMounted(() { window.addEventListener(mousemove, handleMouseMove) }) onUnmounted(() { window.removeEventListener(mousemove, handleMouseMove) }) return { x, y } } // 使用 const { x, y } useMouse() /script template div Mouse position: {{ x }}, {{ y }} /div /template带参数的组合式函数script setup import { ref, onMounted, onUnmounted } from vue // useDebounce组合式函数 function useDebounce(value, delay 300) { const debouncedValue ref(value) let timer null function updateDebouncedValue(newValue) { if (timer) clearTimeout(timer) timer setTimeout(() { debouncedValue.value newValue }, delay) } // 监听值变化 watch(value, (newVal) { updateDebouncedValue(newVal) }) onUnmounted(() { if (timer) clearTimeout(timer) }) return debouncedValue } // 使用 const searchQuery ref() const debouncedQuery useDebounce(searchQuery, 500) /script组合式函数组合script setup import { ref, computed } from vue // useUser组合式函数 function useUser() { const user ref(null) const loading ref(false) async function fetchUser(userId) { loading.value true const response await fetch(/api/users/${userId}) user.value await response.json() loading.value false } return { user, loading, fetchUser } } // usePosts组合式函数 function usePosts(userId) { const posts ref([]) const loading ref(false) async function fetchPosts() { loading.value true const response await fetch(/api/users/${userId.value}/posts) posts.value await response.json() loading.value false } return { posts, loading, fetchPosts } } // 组合使用 const { user, loading: userLoading, fetchUser } useUser() const { posts, loading: postsLoading, fetchPosts } usePosts(computed(() user.value?.id)) onMounted(async () { await fetchUser(1) await fetchPosts() }) /script响应式工具函数isRef、isReactive、isReadonlyscript setup import { ref, reactive, readonly, isRef, isReactive, isReadonly } from vue const count ref(0) const state reactive({ count: 0 }) const readOnlyState readonly(state) console.log(isRef(count)) // true console.log(isReactive(state)) // true console.log(isReadonly(readOnlyState)) // true console.log(isReactive(readOnlyState)) // false /scripttoRef、toRefsscript setup import { reactive, toRef, toRefs } from vue const state reactive({ name: 张三, age: 25 }) // toRef创建单个ref const nameRef toRef(state, name) // 修改ref会影响原对象 nameRef.value 李四 console.log(state.name) // 李四 // toRefs将对象转为ref对象 const refs toRefs(state) console.log(refs.name.value) // 李四 console.log(refs.age.value) // 25 /scriptmarkRaw、shallowRefscript setup import { reactive, markRaw, shallowRef } from vue // markRaw标记为原始值不被响应式系统追踪 const rawObject markRaw({ name: 张三 }) const state reactive({ data: rawObject }) // 修改rawObject不会触发响应 rawObject.name 李四 // 不会触发更新 // shallowRef配合markRaw使用 const config shallowRef(markRaw({ theme: dark, apiUrl: https://api.example.com })) /script生命周期钩子组合式API中的生命周期script setup import { onMounted, onUpdated, onUnmounted } from vue // 挂载后 onMounted(() { console.log(组件挂载完成) }) // 更新后 onUpdated(() { console.log(组件更新完成) }) // 卸载前 onUnmounted(() { console.log(组件即将卸载) }) // 其他钩子 // onBeforeMount // onBeforeUpdate // onBeforeUnmount // onErrorCaptured // onRenderTracked // onRenderTriggered /script生命周期顺序// 创建阶段 // 1. setup() // 2. onBeforeMount // 3. onMounted // 更新阶段 // 1. onBeforeUpdate // 2. 重新执行setup中的响应式代码 // 3. onUpdated // 卸载阶段 // 1. onBeforeUnmount // 2. onUnmounted依赖注入provide和inject!-- 父组件 -- script setup import { provide, ref } from vue const theme ref(light) // 提供值 provide(theme, theme) // 提供方法 provide(toggleTheme, () { theme.value theme.value light ? dark : light }) /script !-- 子组件 -- script setup import { inject } from vue // 注入值 const theme inject(theme) // 注入方法 const toggleTheme inject(toggleTheme) /script template div :classtheme button clicktoggleThemeToggle Theme/button /div /template带默认值的注入script setup import { inject } from vue // 带默认值 const theme inject(theme, light) // 使用工厂函数 const config inject(config, () ({ apiUrl: https://api.example.com })) /script最佳实践1. 组织组合式函数src/ composables/ useMouse.js useDebounce.js useLocalStorage.js useFetch.js2. 单一职责// 好的做法每个组合式函数只做一件事 function useFetch(url) { const data ref(null) const loading ref(false) const error ref(null) async function execute() { loading.value true try { const response await fetch(url) data.value await response.json() } catch (err) { error.value err.message } finally { loading.value false } } return { data, loading, error, execute } }3. 使用TypeScriptimport { ref } from vue interface User { id: number name: string email: string } function useUser(): { user: RefUser | null loading: Refboolean fetchUser: (id: number) Promisevoid } { const user refUser | null(null) const loading ref(false) async function fetchUser(id: number) { loading.value true const response await fetch(/api/users/${id}) user.value await response.json() loading.value false } return { user, loading, fetchUser } }常见问题与解决方案Q1: ref值修改后没有更新视图原因没有使用.value访问ref使用了shallowRef但没有触发更新解决方案确保使用.value使用triggerRef手动触发Q2: watch监听不到嵌套属性变化原因没有设置deep: true使用了shallowReactive解决方案设置deep: true选项使用reactive代替shallowReactiveQ3: 组合式函数中的响应式数据没有正确传递原因没有返回ref或reactive返回了普通对象解决方案返回响应式对象使用toRefs转换总结Vue3组合式API是前端开发的利器基础APIref、reactive、computed、watch进阶APIshallowRef、shallowReactive、readonly组合式函数封装可复用逻辑响应式工具isRef、toRef、toRefs、markRaw生命周期onMounted、onUpdated、onUnmounted依赖注入provide、inject希望今天的分享能帮助你更好地掌握Vue3组合式API如果你有任何问题或建议欢迎在评论区留言关注我每天分享前端干货让我们一起成长
Vue3组合式API进阶:深入理解和高效使用Composition API
Vue3组合式API进阶深入理解和高效使用Composition API前言大家好我是前端老炮儿今天咱们来聊聊Vue3组合式API的进阶用法。你以为ref和reactive就够了那你可太天真了Vue3的Composition API远比你想象的更强大。为什么需要Composition APIOptions API的问题Options API → 逻辑分散 → 难以复用 Options API → 关注点分离 → 阅读困难 Options API → 类型推断差 → 开发体验不佳Composition API的优势逻辑复用变得简单代码组织更加灵活更好的TypeScript支持更细粒度的响应式控制基础API回顾ref和reactivescript setup import { ref, reactive } from vue // ref用于基本类型 const count ref(0) const name ref() // reactive用于对象 const state reactive({ user: { name: 张三, age: 25 }, items: [] }) // 修改ref值 count.value // 修改reactive值 state.user.name 李四 /scriptcomputedscript setup import { ref, computed } from vue const firstName ref(张) const lastName ref(三) // 计算属性 const fullName computed(() { return ${firstName.value}${lastName.value} }) // 可写的计算属性 const fullName2 computed({ get: () ${firstName.value}${lastName.value}, set: (newValue) { const [first, last] newValue.split() firstName.value first lastName.value last } }) /scriptwatch和watchEffectscript setup import { ref, watch, watchEffect } from vue const count ref(0) const name ref() // watch监听特定数据源 watch(count, (newVal, oldVal) { console.log(count changed from ${oldVal} to ${newVal}) }) // 监听多个数据源 watch([count, name], ([newCount, newName], [oldCount, oldName]) { console.log(count: ${oldCount} - ${newCount}) console.log(name: ${oldName} - ${newName}) }) // 深度监听 const state reactive({ user: { name: 张三 } }) watch(state, (newState) { console.log(state changed:, newState) }, { deep: true }) // watchEffect自动追踪依赖 watchEffect(() { console.log(count is: ${count.value}) }) /script进阶APIref进阶script setup import { ref, shallowRef, triggerRef } from vue // shallowRef只追踪顶层值变化 const shallow shallowRef({ name: 张三 }) // 修改嵌套属性不会触发更新 shallow.value.name 李四 // 不会触发更新 // 需要手动触发 triggerRef(shallow) // 触发更新 // ref的特性 const count ref(0) // 获取原始值 console.log(count.value) // 解包 const state reactive({ count }) console.log(state.count) // 自动解包输出0 /scriptreactive进阶script setup import { reactive, shallowReactive, readonly, shallowReadonly } from vue // shallowReactive只响应顶层属性 const shallowState shallowReactive({ user: { name: 张三 } }) // 修改顶层属性会触发更新 shallowState.user { name: 李四 } // 会触发更新 // 修改嵌套属性不会触发更新 shallowState.user.name 王五 // 不会触发更新 // readonly创建只读代理 const state reactive({ count: 0 }) const readOnlyState readonly(state) // 尝试修改会警告 readOnlyState.count // 警告不能修改只读属性 // shallowReadonly只保护顶层 const shallowRead shallowReadonly({ user: { name: 张三 } }) // 顶层不能修改 shallowRead.user {} // 警告 // 嵌套属性可以修改 shallowRead.user.name 李四 // 不会警告 /scriptcomputed进阶script setup import { ref, computed } from vue const items ref([1, 2, 3, 4, 5]) // 计算属性缓存 const doubled computed(() { console.log(computing...) return items.value.map(item item * 2) }) // 只有依赖变化时才重新计算 console.log(doubled.value) // 输出: computing... [2,4,6,8,10] console.log(doubled.value) // 输出: [2,4,6,8,10] (没有重新计算) // 计算属性作为依赖 const sum computed(() { return doubled.value.reduce((acc, val) acc val, 0) }) console.log(sum.value) // 30 /scriptwatch进阶script setup import { ref, watch, watchEffect } from vue const count ref(0) // 立即执行 watch(count, (newVal) { console.log(count:, newVal) }, { immediate: true }) // 深度监听 const state reactive({ nested: { value: 0 } }) watch(state, (newState) { console.log(nested value:, newState.nested.value) }, { deep: true }) // 停止监听 const stop watch(count, (newVal) { console.log(count changed:, newVal) }) // 停止监听 stop() // watchEffect清理 watchEffect((onCleanup) { const timer setTimeout(() { console.log(done) }, 1000) // 清理函数 onCleanup(() { clearTimeout(timer) }) }) /script组合式函数创建组合式函数script setup import { ref, onMounted, onUnmounted } from vue // useMouse组合式函数 function useMouse() { const x ref(0) const y ref(0) function handleMouseMove(e) { x.value e.clientX y.value e.clientY } onMounted(() { window.addEventListener(mousemove, handleMouseMove) }) onUnmounted(() { window.removeEventListener(mousemove, handleMouseMove) }) return { x, y } } // 使用 const { x, y } useMouse() /script template div Mouse position: {{ x }}, {{ y }} /div /template带参数的组合式函数script setup import { ref, onMounted, onUnmounted } from vue // useDebounce组合式函数 function useDebounce(value, delay 300) { const debouncedValue ref(value) let timer null function updateDebouncedValue(newValue) { if (timer) clearTimeout(timer) timer setTimeout(() { debouncedValue.value newValue }, delay) } // 监听值变化 watch(value, (newVal) { updateDebouncedValue(newVal) }) onUnmounted(() { if (timer) clearTimeout(timer) }) return debouncedValue } // 使用 const searchQuery ref() const debouncedQuery useDebounce(searchQuery, 500) /script组合式函数组合script setup import { ref, computed } from vue // useUser组合式函数 function useUser() { const user ref(null) const loading ref(false) async function fetchUser(userId) { loading.value true const response await fetch(/api/users/${userId}) user.value await response.json() loading.value false } return { user, loading, fetchUser } } // usePosts组合式函数 function usePosts(userId) { const posts ref([]) const loading ref(false) async function fetchPosts() { loading.value true const response await fetch(/api/users/${userId.value}/posts) posts.value await response.json() loading.value false } return { posts, loading, fetchPosts } } // 组合使用 const { user, loading: userLoading, fetchUser } useUser() const { posts, loading: postsLoading, fetchPosts } usePosts(computed(() user.value?.id)) onMounted(async () { await fetchUser(1) await fetchPosts() }) /script响应式工具函数isRef、isReactive、isReadonlyscript setup import { ref, reactive, readonly, isRef, isReactive, isReadonly } from vue const count ref(0) const state reactive({ count: 0 }) const readOnlyState readonly(state) console.log(isRef(count)) // true console.log(isReactive(state)) // true console.log(isReadonly(readOnlyState)) // true console.log(isReactive(readOnlyState)) // false /scripttoRef、toRefsscript setup import { reactive, toRef, toRefs } from vue const state reactive({ name: 张三, age: 25 }) // toRef创建单个ref const nameRef toRef(state, name) // 修改ref会影响原对象 nameRef.value 李四 console.log(state.name) // 李四 // toRefs将对象转为ref对象 const refs toRefs(state) console.log(refs.name.value) // 李四 console.log(refs.age.value) // 25 /scriptmarkRaw、shallowRefscript setup import { reactive, markRaw, shallowRef } from vue // markRaw标记为原始值不被响应式系统追踪 const rawObject markRaw({ name: 张三 }) const state reactive({ data: rawObject }) // 修改rawObject不会触发响应 rawObject.name 李四 // 不会触发更新 // shallowRef配合markRaw使用 const config shallowRef(markRaw({ theme: dark, apiUrl: https://api.example.com })) /script生命周期钩子组合式API中的生命周期script setup import { onMounted, onUpdated, onUnmounted } from vue // 挂载后 onMounted(() { console.log(组件挂载完成) }) // 更新后 onUpdated(() { console.log(组件更新完成) }) // 卸载前 onUnmounted(() { console.log(组件即将卸载) }) // 其他钩子 // onBeforeMount // onBeforeUpdate // onBeforeUnmount // onErrorCaptured // onRenderTracked // onRenderTriggered /script生命周期顺序// 创建阶段 // 1. setup() // 2. onBeforeMount // 3. onMounted // 更新阶段 // 1. onBeforeUpdate // 2. 重新执行setup中的响应式代码 // 3. onUpdated // 卸载阶段 // 1. onBeforeUnmount // 2. onUnmounted依赖注入provide和inject!-- 父组件 -- script setup import { provide, ref } from vue const theme ref(light) // 提供值 provide(theme, theme) // 提供方法 provide(toggleTheme, () { theme.value theme.value light ? dark : light }) /script !-- 子组件 -- script setup import { inject } from vue // 注入值 const theme inject(theme) // 注入方法 const toggleTheme inject(toggleTheme) /script template div :classtheme button clicktoggleThemeToggle Theme/button /div /template带默认值的注入script setup import { inject } from vue // 带默认值 const theme inject(theme, light) // 使用工厂函数 const config inject(config, () ({ apiUrl: https://api.example.com })) /script最佳实践1. 组织组合式函数src/ composables/ useMouse.js useDebounce.js useLocalStorage.js useFetch.js2. 单一职责// 好的做法每个组合式函数只做一件事 function useFetch(url) { const data ref(null) const loading ref(false) const error ref(null) async function execute() { loading.value true try { const response await fetch(url) data.value await response.json() } catch (err) { error.value err.message } finally { loading.value false } } return { data, loading, error, execute } }3. 使用TypeScriptimport { ref } from vue interface User { id: number name: string email: string } function useUser(): { user: RefUser | null loading: Refboolean fetchUser: (id: number) Promisevoid } { const user refUser | null(null) const loading ref(false) async function fetchUser(id: number) { loading.value true const response await fetch(/api/users/${id}) user.value await response.json() loading.value false } return { user, loading, fetchUser } }常见问题与解决方案Q1: ref值修改后没有更新视图原因没有使用.value访问ref使用了shallowRef但没有触发更新解决方案确保使用.value使用triggerRef手动触发Q2: watch监听不到嵌套属性变化原因没有设置deep: true使用了shallowReactive解决方案设置deep: true选项使用reactive代替shallowReactiveQ3: 组合式函数中的响应式数据没有正确传递原因没有返回ref或reactive返回了普通对象解决方案返回响应式对象使用toRefs转换总结Vue3组合式API是前端开发的利器基础APIref、reactive、computed、watch进阶APIshallowRef、shallowReactive、readonly组合式函数封装可复用逻辑响应式工具isRef、toRef、toRefs、markRaw生命周期onMounted、onUpdated、onUnmounted依赖注入provide、inject希望今天的分享能帮助你更好地掌握Vue3组合式API如果你有任何问题或建议欢迎在评论区留言关注我每天分享前端干货让我们一起成长