Vue3组合式API精解:十大核心函数详析
2025.09.18 18:04浏览量:0简介:本文深度解析Vue3中最常用的10个组合式API,涵盖响应式控制、生命周期、依赖注入等核心功能,通过代码示例和场景分析帮助开发者快速掌握组合式编程范式。
Vue3组合式API精解:十大核心函数详析
Vue3的组合式API(Composition API)通过逻辑复用和更灵活的代码组织方式,彻底改变了Vue应用的开发模式。本文将深入解析10个最常用的组合式API,从基础响应式到高级依赖注入,结合实际场景和代码示例,帮助开发者系统掌握组合式编程范式。
一、响应式控制核心API
1. ref:创建响应式引用
ref
是组合式API的基础构建块,用于创建可响应的单一值引用。其核心特性包括:
import { ref } from 'vue'
const count = ref(0) // 创建响应式数字
const text = ref('') // 创建响应式字符串
// 修改值必须通过.value
function increment() {
count.value++
}
在模板中,ref会自动解包,无需.value
访问。适用于表单输入、计数器等简单状态管理。建议将ref与类型定义结合使用(TypeScript环境下):
const userAge = ref<number>(25)
2. reactive:创建响应式对象
reactive
用于创建深层响应式的对象,特别适合管理复杂状态:
import { reactive } from 'vue'
const state = reactive({
user: {
name: 'Alice',
age: 30
},
preferences: {
theme: 'dark'
}
})
// 深层响应式
function updateUser() {
state.user.name = 'Bob' // 自动触发更新
state.preferences.theme = 'light'
}
注意:reactive对象解构后会失去响应性,如需解构应使用toRefs
:
import { toRefs } from 'vue'
const { user, preferences } = toRefs(state)
3. computed:创建计算属性
computed
提供响应式依赖的计算值,具有缓存特性:
import { computed, ref } from 'vue'
const price = ref(100)
const quantity = ref(2)
const total = computed(() => price.value * quantity.value)
// 带写入的计算属性
const discountedPrice = computed({
get: () => price.value * 0.9,
set: (newValue) => {
price.value = newValue / 0.9
}
})
计算属性在依赖不变时不会重复计算,适合处理复杂逻辑的派生状态。
二、生命周期与副作用管理
4. onMounted:组件挂载钩子
onMounted
是组合式API中最常用的生命周期钩子,替代Options API的mounted
:
import { onMounted } from 'vue'
export default {
setup() {
onMounted(() => {
console.log('组件已挂载')
// 执行DOM操作或数据初始化
})
}
}
与nextTick
结合可确保DOM更新完成:
import { nextTick } from 'vue'
onMounted(async () => {
await nextTick()
const element = document.getElementById('target')
// 安全操作DOM
})
5. watch & watchEffect:响应式监听
watch
和watchEffect
提供精细的响应式依赖追踪:
import { watch, watchEffect, ref } from 'vue'
const count = ref(0)
const double = computed(() => count.value * 2)
// 精确监听特定ref
watch(count, (newVal, oldVal) => {
console.log(`count变化: ${oldVal} -> ${newVal}`)
})
// 自动追踪依赖
watchEffect(() => {
console.log(`double值: ${double.value}`)
// 会自动追踪double.value的依赖
})
watch
适合需要新旧值对比的场景,watchEffect
适合立即执行的副作用。
三、依赖注入与上下文管理
6. provide & inject:跨组件通信
组合式API中的provide/inject
提供了更灵活的依赖注入机制:
// 父组件
import { provide, ref } from 'vue'
const theme = ref('dark')
provide('theme', theme)
// 子组件
import { inject } from 'vue'
const theme = inject('theme', 'light') // 默认值'light'
结合响应式对象可实现动态主题切换:
// 父组件
provide('themeSettings', reactive({
theme: 'dark',
fontSize: 16
}))
// 子组件
const { theme, fontSize } = inject('themeSettings')
7. useContext:访问组件上下文
在自定义组合函数中,可通过getCurrentInstance
访问组件上下文(Vue3.3+推荐使用useContext
替代):
import { getCurrentInstance } from 'vue'
export function useLogger() {
const instance = getCurrentInstance()
return {
log: (message) => {
if (instance?.proxy) {
console.log(`[${instance.proxy.$options.name}] ${message}`)
}
}
}
}
注意:在SSR环境中需谨慎使用上下文访问。
四、高级功能组合
8. onBeforeUnmount:清理资源
组合式API中的资源清理钩子:
import { onBeforeUnmount } from 'vue'
export default {
setup() {
const timer = setInterval(() => {
console.log('心跳检测')
}, 5000)
onBeforeUnmount(() => {
clearInterval(timer) // 必须清理
})
}
}
适用于事件监听器、定时器、WebSocket连接等资源的释放。
9. customRef:自定义响应式引用
customRef
提供对ref行为的完全控制:
import { customRef } from 'vue'
function useDebouncedRef(value, delay = 200) {
let timeout
return customRef((track, trigger) => {
return {
get() {
track()
return value
},
set(newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
}
}
})
}
// 使用防抖ref
const searchQuery = useDebouncedRef('')
适用于输入防抖、节流等场景。
10. Suspense相关API:异步组件控制
Vue3的Suspense
组件配合组合式API处理异步依赖:
// AsyncComponent.vue
import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() =>
import('./HeavyComponent.vue')
)
// 父组件中使用Suspense
<template>
<Suspense>
<template #default>
<AsyncComp />
</template>
<template #fallback>
<div>加载中...</div>
</template>
</Suspense>
</template>
组合式API中可通过resolveComponent
动态加载组件:
import { resolveComponent } from 'vue'
const compName = ref('AsyncComp')
const DynamicComp = computed(() => resolveComponent(compName.value))
最佳实践建议
- 状态组织:按逻辑而非组件结构组织代码,使用
setup()
函数或<script setup>
语法 - 类型安全:为ref和reactive对象添加TypeScript类型定义
- 性能优化:对频繁更新的计算属性使用
shallowRef
或shallowReactive
- 组合函数:将通用逻辑封装为可复用的组合函数(如
useFetch
、useLocalStorage
) - SSR兼容:避免在服务端渲染时访问浏览器API
通过系统掌握这10个核心组合式API,开发者能够构建出更模块化、可维护的Vue3应用。组合式API的灵活性尤其适合中大型项目的开发,建议结合Vue Devtools进行状态调试和性能分析。
发表评论
登录后可评论,请前往 登录 或 注册