Vue3组合式函数实战:5个高效逻辑复用技巧
1. 基础组合式函数:鼠标跟踪
创建可复用的鼠标位置跟踪逻辑:
// useMousePosition.js
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 }
}
// 组件中使用
const { x, y } = useMousePosition()
2. 异步数据加载
封装数据请求逻辑:
// 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 }
}
// 组件中使用
const { data, loading, fetchData } = useFetch('/api/products')
fetchData()
3. 购物车逻辑封装
实现电商购物车功能:
// useCart.js
import { ref, computed } from 'vue'
export function useCart() {
const items = ref([])
const total = computed(() =>
items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
)
const addItem = (product) => {
const existing = items.value.find(i => i.id === product.id)
if (existing) {
existing.quantity++
} else {
items.value.push({ ...product, quantity: 1 })
}
}
return { items, total, addItem }
}
4. 本地存储集成
自动同步状态到localStorage:
// useLocalStorage.js
import { ref, watch } from 'vue'
export function useLocalStorage(key, initialValue) {
const stored = localStorage.getItem(key)
const data = ref(stored ? JSON.parse(stored) : initialValue)
watch(data, (value) => {
localStorage.setItem(key, JSON.stringify(value))
}, { deep: true })
return data
}
// 组件中使用
const darkMode = useLocalStorage('darkMode', false)
复用方式 | Options API | 组合式函数 |
---|---|---|
代码组织 | 按选项分组 | 按功能组织 |
逻辑复用 | Mixins/高阶组件 | 直接函数调用 |
类型支持 | 有限 | 完善 |
5. 组合式函数组合
构建复杂业务逻辑:
// useProductListing.js
import { computed } from 'vue'
import { useFetch } from './useFetch'
import { useCart } from './useCart'
export function useProductListing() {
const { data: products, fetchData } = useFetch('/api/products')
const { addItem } = useCart()
const featuredProducts = computed(() =>
products.value?.filter(p => p.featured) || []
)
return { products, featuredProducts, fetchData, addItem }
}
// 组件中使用
const { featuredProducts, addItem } = useProductListing()
通过合理使用组合式函数,可以将复杂业务逻辑拆分为可维护的小单元,大幅提升Vue3应用的开发效率和代码质量。