add. Closes #8
All checks were successful
Deploy Nuxt App / deploy (push) Successful in 3m59s
All checks were successful
Deploy Nuxt App / deploy (push) Successful in 3m59s
This commit is contained in:
58
store/useSelectedBook.ts
Normal file
58
store/useSelectedBook.ts
Normal file
@ -0,0 +1,58 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
interface CartItem {
|
||||
id: number
|
||||
quantity: number
|
||||
summary?: number
|
||||
}
|
||||
|
||||
export const useSelectedBook = defineStore('selectedBook', {
|
||||
state: () => ({
|
||||
cartQuantities: [] as CartItem[],
|
||||
}),
|
||||
actions: {
|
||||
increment(id: number) {
|
||||
const item = this.cartQuantities.find((i) => i.id === id)
|
||||
if (item && item.quantity < 1) {
|
||||
item.quantity++
|
||||
}
|
||||
},
|
||||
decrement(id: number) {
|
||||
const item = this.cartQuantities.find((i) => i.id === id)
|
||||
if (item) {
|
||||
item.quantity--
|
||||
}
|
||||
},
|
||||
reset(id: number) {
|
||||
const idx = this.cartQuantities.findIndex((i) => i.id === id)
|
||||
if (idx !== -1) {
|
||||
this.cartQuantities.splice(idx, 1)
|
||||
}
|
||||
},
|
||||
addToCart(id: number) {
|
||||
if (!this.cartQuantities.find((i) => i.id === id)) {
|
||||
this.cartQuantities.push({ id, quantity: 1 })
|
||||
}
|
||||
},
|
||||
getQuantity(id: number) {
|
||||
return this.cartQuantities.find((i) => i.id === id)?.quantity || 0
|
||||
},
|
||||
},
|
||||
getters: {
|
||||
getTotalPrice: (state) => (books: { id: number; price: number }[]) => {
|
||||
const selected = state.cartQuantities.filter((i) => i.quantity > 0)
|
||||
if (selected.length === 2) {
|
||||
// Проверяем, что это две разные книги
|
||||
const ids = selected.map((i) => i.id)
|
||||
if (ids[0] !== ids[1]) {
|
||||
return 936
|
||||
}
|
||||
}
|
||||
// Обычная сумма
|
||||
return selected.reduce((sum, item) => {
|
||||
const book = books.find((b) => b.id === item.id)
|
||||
return sum + (book ? book.price * item.quantity : 0)
|
||||
}, 0)
|
||||
},
|
||||
},
|
||||
})
|
Reference in New Issue
Block a user