useFavorite.js
1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @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