/
favorite.js
37 lines (37 loc) · 1005 Bytes
/
favorite.js
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
import { defineStore } from 'pinia'
import { Toast } from '../../src/methods/swalToast';
const favoritesStore = defineStore('favoritesStore', {
state: () => {
return {
favoritesList: JSON.parse(localStorage.getItem('favoritesList')) || []
}
},
actions: {
toggleFavorite(product) {
const favoriteIndex = this.favoritesList.findIndex((item) => item.id === product.id)
if (favoriteIndex === -1) {
this.favoritesList.push(product)
Toast.fire({
icon: 'success',
title: '加入收藏'
})
} else {
this.favoritesList.splice(favoriteIndex, 1)
Toast.fire({
icon: 'success',
title: '取消收藏'
})
}
},
isFavorite(product) {
return this.favoritesList.some((item) => item.id === product.id)
}
},
getters: {
getFavoritesNum: ({ favoritesList }) => {
return favoritesList.length
}
},
deep: ['favoritesList']
})
export default favoritesStore