Vue3组合式函数实战:企业级逻辑复用架构设计
一、架构优势
组合式函数使业务逻辑复用率提升300%,代码维护成本降低60%
// 传统Options API vs 组合式函数
export default { | export function useUser() {
data() { return {...} } | const user = ref(null)
methods: { ... } | const fetchUser = async () => {...}
} | return { user, fetchUser }
|
二、核心设计
1. 基础组合函数
// useFetch.js
import { ref } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
const fetchData = async () => {
loading.value = true
try {
const response = await fetch(url)
data.value = await response.json()
} catch (err) {
error.value = err
} finally {
loading.value = false
}
}
return { data, error, loading, fetchData }
}
2. 嵌套组合函数
// useAuth.js
import { useFetch } from './useFetch'
export function useAuth() {
const { data: user, fetchData: fetchUser } = useFetch('/api/user')
const isAdmin = computed(() => user.value?.role === 'admin')
const login = async (credentials) => {
await useFetch('/api/login').fetchData(credentials)
await fetchUser()
}
return { user, isAdmin, login }
}
三、企业级实践
1. 权限管理系统
// usePermission.js
import { computed } from 'vue'
import { useAuth } from './useAuth'
export function usePermission() {
const { user } = useAuth()
const permissions = computed(() => user.value?.permissions || [])
const hasPermission = (required) => {
return computed(() =>
permissions.value.includes(required) ||
permissions.value.includes('admin')
).value
}
return { hasPermission }
}
2. 全局状态共享
// useStore.js
import { provide, inject } from 'vue'
const StoreSymbol = Symbol()
export function provideStore(store) {
provide(StoreSymbol, store)
}
export function useStore() {
const store = inject(StoreSymbol)
if (!store) throw new Error('未注入Store!')
return store
}
// 根组件
const store = reactive({...})
provideStore(store)
// 子组件
const store = useStore()
四、完整案例
数据分析看板系统
// useDashboard.js
import { ref, computed } from 'vue'
import { useFetch } from './useFetch'
export function useDashboard() {
const dateRange = ref(['2023-01-01', '2023-12-31'])
const {
data: rawData,
loading,
fetchData
} = useFetch('/api/analytics')
const metrics = computed(() => {
if (!rawData.value) return []
return transformData(rawData.value, dateRange.value)
})
const refresh = () => fetchData({
params: {
start: dateRange.value[0],
end: dateRange.value[1]
}
})
return { dateRange, metrics, loading, refresh }
}
// 组件使用
const { dateRange, metrics, refresh } = useDashboard()