<template>
<div id="app">
<h1>购物车</h1>
<div>
<p>购物车商品总数:{
{ itemCount }}</p>
<p>购物车总价:{
{ totalPrice }} 元</p>
</div>
<div>
<button @click="addItemToCart">添加商品</button>
<button @click="removeItemFromCart">删除商品</button>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
// 使用命名空间,映射 cart 模块的状态
...mapState('cart', ['items']),
itemCount() {
return this.$store.getters['cart/itemCount'] // 获取购物车商品总数
},
totalPrice() {
return this.$store.getters['cart/totalPrice'] // 获取购物车总价
}
},
methods: {
...mapActions('cart', ['addItemAsync', 'removeItemAsync']), // action 方法映射
addItemToCart() {
const newItem = { id: 1, name: '商品A', price: 100, quantity: 1 }
this.addItemAsync(newItem)
},
removeItemFromCart() {
this.removeItemAsync(1)
}
}
}
</script>