Vue3组合式函数实战:5个高效逻辑复用技巧 | Vue3高级开发

2025-07-16 0 816

Vue3组合式函数实战:5个高效逻辑复用技巧

核心价值: Vue3的组合式API彻底改变了逻辑复用的方式。本文将展示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应用的开发效率和代码质量。

Vue3组合式函数实战:5个高效逻辑复用技巧 | Vue3高级开发
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 vue3 Vue3组合式函数实战:5个高效逻辑复用技巧 | Vue3高级开发 https://www.taomawang.com/web/vue3/378.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务