Vue 3自定义Hooks完全指南:从基础到高级,提升你的开发效率!
在Vue 3中,Composition API的引入为组件逻辑的复用和组织带来了全新的方式,而Hooks则是这一API中的重要概念。通过自定义Hooks,我们可以更好地提取和复用组件逻辑,保持状态的响应性,并实现关注点分离。本文将从基础概念出发,逐步深入到高级模式和最佳实践,帮助你全面掌握Vue 3自定义Hooks的使用。
一、Hooks基础概念
1.什么是Hooks
Hooks是Vue 3 Composition API中的一个重要概念,它允许我们:
- 提取和复用组件逻辑
- 保持状态的响应性
- 实现关注点分离
2.Hooks的特点
// 基本结构示例
import { ref, onMounted, onUnmounted } from 'vue'
export function useMousePosition() {
// 状态
const x = ref(0)
const y = ref(0)
// 方法
const update = (e) => {
x.value = e.pageX
y.value = e.pageY
}
// 生命周期
onMounted(() => {
window.addEventListener('mousemove', update)
})
onUnmounted(() => {
window.removeEventListener('mousemove', update)
})
// 返回状态和方法
return { x, y }
}
二、常用Hooks实现
1.网络请求Hook
// hooks/useRequest.ts
import { ref, shallowRef } from 'vue'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface RequestOptions extends AxiosRequestConfig {
immediate?: boolean
onSuccess?: (data: any) => void
onError?: (error: any) => void
}
export function useRequest<T = any>(
url: string,
options: RequestOptions = {}
) {
const data = shallowRef<T | null>(null)
const error = shallowRef<any>(null)
const loading = ref(false)
const {
immediate = true,
onSuccess,
onError,
...axiosConfig
} = options
const execute = async () => {
loading.value = true
error.value = null
try {
const response = await axios.request<T>({
url,
...axiosConfig
})
data.value = response.data
onSuccess?.(response.data)
return response
} catch (err) {
error.value = err
onError?.(err)
throw err
} finally {
loading.value = false
}
}
if (immediate) {
execute()
}
return {
data,
error,
loading,
execute
}
}
// 使用示例
const {
data: users,
loading,
error,
execute: fetchUsers
} = useRequest<User[]>('/api/users', {
immediate: false,
onSuccess: (data) => {
console.log('Users loaded:', data)
}
})
2.状态管理Hook
// hooks/useState.ts
import { reactive, readonly } from 'vue'
export function useState<T extends object>(
initialState: T,
options: {
persist?: boolean
key?: string
} = {}
) {
const { persist = false, key = 'app_state' } = options
// 初始化状态
const state = reactive({
...initialState,
...(persist ? JSON.parse(localStorage.getItem(key) || '{}') : {})
})
// 修改状态方法
const setState = (partial: Partial<T> | ((state: T) => Partial<T>)) => {
const newState = typeof partial === 'function' ? partial(state) : partial
Object.assign(state, newState)
if (persist) {
localStorage.setItem(key, JSON.stringify(state))
}
}
// 重置状态
const resetState = () => {
Object.assign(state, initialState)
if (persist) {
localStorage.removeItem(key)
}
}
return {
state: readonly(state),
setState,
resetState
}
}
// 使用示例
const {
state: userState,
setState: setUserState,
resetState: resetUserState
} = useState({
name: '',
age: 0,
preferences: {}
}, {
persist: true,
key: 'user_state'
})
3.DOM操作Hook
// hooks/useElementSize.ts
import { ref, onMounted, onUnmounted } from 'vue'
export function useElementSize() {
const element = ref<HTMLElement | null>(null)
const width = ref(0)
const height = ref(0)
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
const { contentRect } = entry
width.value = contentRect.width
height.value = contentRect.height
}
})
onMounted(() => {
if (element.value) {
observer.observe(element.value)
}
})
onUnmounted(() => {
observer.disconnect()
})
return {
element,
width,
height
}
}
// 使用示例
const { element, width, height } = useElementSize()
</script>
<template>
<div ref="element">
Size: {{ width }} x {{ height }}
</div>
</template>
4.表单处理Hook
// hooks/useForm.ts
import { reactive, computed } from 'vue'
interface FormOptions<T> {
initialValues: T
validate?: (values: T) => Promise<void>
onSubmit?: (values: T) => Promise<void>
}
export function useForm<T extends object>({
initialValues,
validate,
onSubmit
}: FormOptions<T>) {
const values = reactive({ ...initialValues })
const errors = reactive<Record<string, string>>({})
const touched = reactive<Record<string, boolean>>({})
const dirty = computed(() =>
Object.keys(initialValues).some(key =>
values[key as keyof T] !== initialValues[key as keyof T]
)
)
const handleSubmit = async () => {
try {
if (validate) {
await validate(values)
}
if (onSubmit) {
await onSubmit(values)
}
} catch (error) {
if (error instanceof Error) {
errors['form'] = error.message
}
}
}
const handleReset = () => {
Object.assign(values, initialValues)
Object.keys(errors).forEach(key => delete errors[key])
Object.keys(touched).forEach(key => delete touched[key])
}
const setFieldValue = (field: keyof T, value: any) => {
values[field] = value
}
const setFieldTouched = (field: keyof T, isTouched = true) => {
touched[field] = isTouched
}
return {
values,
errors,
touched,
dirty,
handleSubmit,
handleReset,
setFieldValue,
setFieldTouched
}
}
// 使用示例
const {
values,
errors,
touched,
handleSubmit
} = useForm({
initialValues: {
username: '',
password: ''
},
validate: async (values) => {
if (!values.username) {
throw new Error('Username is required')
}
},
onSubmit: async (values) => {
await api.login(values)
}
})
三、高级Hooks模式
1.组合Hooks
// hooks/useUserProfile.ts
export function useUserProfile(userId: string) {
// 组合多个基础Hooks
const { data: user, loading: userLoading } = useRequest(
`/api/users/${userId}`
)
const { data: posts, loading: postsLoading } = useRequest(
`/api/users/${userId}/posts`
)
const loading = computed(() => userLoading.value || postsLoading.value)
return {
user,
posts,
loading
}
}
2.条件Hooks
// hooks/useConditional.ts
export function useConditionalFetch<T>(
url: string,
condition: () => boolean
) {
const { data, execute } = useRequest<T>(url, { immediate: false })
watch(
condition,
(value) => {
if (value) {
execute()
}
},
{ immediate: true }
)
return { data }
}
3.缓存Hooks
// hooks/useCache.ts
export function useCache<T>(
key: string,
factory: () => Promise<T>,
options: {
ttl?: number
} = {}
) {
const cache = new Map<string, {
data: T
timestamp: number
}>()
const getData = async () => {
const cached = cache.get(key)
if (cached && Date.now() - cached.timestamp < (options.ttl || 5000)) {
return cached.data
}
const data = await factory()
cache.set(key, {
data,
timestamp: Date.now()
})
return data
}
return { getData }
}
四、性能优化
1.避免重复创建
// 使用Symbol确保唯一性
const stateSymbol = Symbol('state')
export function useState() {
const vm = getCurrentInstance()
if (!vm) {
throw new Error('useState must be called inside setup')
}
// 检查是否已存在
if (vm[stateSymbol]) {
return vm[stateSymbol]
}
// 创建新实例
const state = reactive({})
vm[stateSymbol] = state
return state
}
2.合理使用shallowRef
// 对于大型对象使用shallowRef
export function useLargeData() {
const data = shallowRef<BigData | null>(null)
const setData = (newData: BigData) => {
data.value = newData
}
return {
data,
setData
}
}
五、最佳实践
- 命名规范
- 使用use前缀
- 驼峰命名
- 语义化
- 返回值规范
- 返回对象而不是数组
- 提供完整的类型定义
- 保持一致的命名
- 错误处理
- 提供错误状态
- 合理的异常捕获
- 友好的错误信息
- 生命周期处理
- 及时清理副作用
- 避免内存泄漏
- 处理组件卸载
总结
本指南涵盖了:
- Hooks的基本概念和使用
- 常用Hooks的实现
- 高级Hooks模式
- 性能优化策略
- 最佳实践建议
关键点:
- 逻辑复用
- 状态管理
- 性能优化
- 代码组织