动态统计购物车中商品的总数量
- 在 vuex 里的getters 节点下定义一个 total 方法,用来统计购物车中商品的总数量:
// 模块的 getters 属性
getters: {
// 统计购物车中商品的总数量
total(state) {
let c = 0
// 循环统计商品的数量,累加到变量 c 中
state.cart.forEach(goods => c += goods.goods_count)
return c
}
}
- 在商品详情页面的 script 标签中,按需导入 mapGetters 方法并进行使用:
// 按需导入 mapGetters 这个辅助方法
import { mapGetters } from 'vuex'
export default {
computed: {
// 把 m_cart 模块中名称为 total 的 getter 映射到当前页面中使用
...mapGetters('m_cart', ['total']),
},
}
3.通过 watch 侦听器,监听计算属性 total 值的变化,从而动态为购物车按钮的徽标赋值:
export default {
watch: {
// 1. 监听 total 值的变化,通过第一个形参得到变化后的新值
total(newVal) {
// 2. 通过数组的 find() 方法,找到购物车按钮的配置对象
const findResult = this.options.find((x) => x.text === '购物车')
if (findResult) {
// 3. 动态为购物车按钮的 info 属性赋值
findResult.info = newVal
}
},
},
}