vuex全家桶系列-vuex购物车案例-购物车中数据渲染

278 阅读1分钟

vuex全家桶系列06-vuex购物车案例-购物车中数据渲染

1.购物车中的数据渲染

  • 通过 mapGetters 去拿到 cart 模块中的 getCartList
<template>
  <div>
    我是购物车组件
    <ul>
      <li
        v-for="(item) in getCartList"
        :key="item.id"
      >{{item.title}}--{{item.price}} X {{item.quantity}}</li>
    </ul>

  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex';
export default {
  name: 'ShoppCart',
  computed: {
    ...mapState('products', ['products']),
    ...mapGetters('cart', ['getCartList']),
  },
};
</script>

<style lang="scss" scoped>
</style>

  • getCartList 中有第三个参数 rootState,拿到的是 store 根目录的 index.js;
    • 🤣获取其他模块的数据:rootState + 模块名字 + 属性名字,例如:rootState.products.products 获得的是 products模块products数组的内容
  • 特别注意 cartList 中的值,需要有个默认的值,因为获取到数据之前,先跑的 conputed 的默认值,拿到请求数据后再次渲染。
export default {
    namespaced:true,
    state:{
        count:0,
      //🐳cartList中的值
        cartList:[    
        {
            id:1,
            title:"iphone12",
            price:1200,
            quantity:12
        }]
    },
    getters:{
        //🌵这里主要看这个
        getCartList(state,getters,rootState){
            return state.cartList.map(({id,quantity})=>{
                const product = rootState.products.products.find(item=> item.id === id);
                    return {
                        title:product.title,
                        price:product.price,
                        quantity
                    }
            })
        },
    },
    mutations:{
        addProductToCart(state,{id,quantity}){
            // state.cartList = product;
            state.cartList.push({id,quantity});
        },
        incrementCartQuantity(state,{id}){
            const curItem = state.cartList.find(item=>item.id===id);
            curItem.quantity++;
        }
    },
    actions:{
        addProduct({commit,state},product){
            console.log("我是actions中的product",product);
            if(product.inventory > 0)//有库存
            {
                const cartItem  = state.cartList.find(item=>{
                    return item.id === product.id 
                });
                console.log("我是数组find方法的返回值",cartItem);
                //购物车中没有数据,新添加到购物车
                if(!cartItem)
                {
                    commit("addProductToCart",{id:product.id,quantity:1});
                }else{
                    //购物车中已有数据
                    commit("incrementCartQuantity",{id:product.id})
                }
            }
            // commit("addProductToCart",product);
        }
    }
}