useFavorite.js 1.74 KB
/*
 * @Date: 2025-07-10 21:28:57
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-07-10 21:59:52
 * @FilePath: /jgdl/src/composables/useFavorite.js
 * @Description: 文件描述
 */
import Taro from '@tarojs/taro'
import { toggleFavoriteAddAPI, toggleFavoriteDelAPI } from '@/api/other';

/**
 * 收藏功能的composables - 基于对象属性的模式
 * 支持对象的is_favorite属性进行收藏状态管理
 */
export function useFavorite() {
    /**
     * 切换收藏状态
     * @param {Object} item - 包含is_favorite属性的对象
     */
    const toggleFavorite = async (item) => {
        if (!item.is_favorite) {
            const { code } = await toggleFavoriteAddAPI({
                vehicle_id: item.id,
            })
            if (code) {
                item.is_favorite = !item.is_favorite
                Taro.showToast({
                    title: '收藏成功',
                    icon: 'success',
                    duration: 2000
                })
            }
        } else {
            const { code } = await toggleFavoriteDelAPI({
                vehicle_id: item.id,
            })
            if (code) {
                item.is_favorite = !item.is_favorite
                Taro.showToast({
                    title: '取消收藏',
                    icon: 'none',
                    duration: 2000
                })
            }
        }
    }

    /**
     * 检查是否已收藏
     * @param {Object} item - 包含is_favorite属性的对象
     * @returns {boolean} 是否已收藏
     */
    const isFavorite = (item) => {
        return item.is_favorite || false
    }

    return {
        toggleFavorite,
        isFavorite
    }
}

// 设置useFavorite为默认导出
export default useFavorite