store/modules/products.js
export default {
namespaced: true,
state: {
products: [
{ id: 1, name: '商品1', price: 100, stock: 10 },
{ id: 2, name: '商品2', price: 200, stock: 5 }
]
},
mutations: {
UPDATE_STOCK(state, { id, quantity }) {
const product = state.products.find(p => p.id === id)
if (product) {
product.stock -= quantity
}
}
}
}
store/modules/cart.js
export default {
namespaced: true,
state: {
items: []
},
mutations: {
ADD_TO_CART(state, { product, quantity }) {
const existingItem = state.items.find(item => item.id === product.id)
if (existingItem) {
existingItem.quantity += quantity
} else {
state.items.push({
id: product.id,
name: product.name,
price: product.price,
quantity
})
}
},
REMOVE_FROM_CART(state, id) {
state.items = state.items.filter(item => item.id !== id)
},
UPDATE_QUANTITY(state, { id, quantity }) {
const item = state.items.find(item => item.id === id)
if (item) {
item.quantity = quantity
}
}
},
actions: {
addToCart({ commit, rootState }, { productId, quantity }) {
const product = rootState.products.products.find(p => p.id === productId)
if (product && product.stock >= quantity) {
commit('ADD_TO_CART', { product, quantity })
commit('products/UPDATE_STOCK', { id: productId, quantity }, { root: true })
}
}
},
getters: {
cartItems: state => state.items,
cartTotal: state => state.items.reduce((total, item) => total + item.price * item.quantity, 0),
cartItemCount: state => state.items.reduce((count, item) => count + item.quantity, 0)
}
}