个人玩耍VUE..我的点点滴滴,今天很冷,2度!!!


谢谢博客园,可以记录我的点点滴滴。!!这个小案例的效果图

其中,这篇还是上一篇博客的序章,我们直接看下更新的代码。

Cart.Vue



  Cart.js

import API from '../../utils/api'

var api = new API('cart');

const state={
    List:[],
    LocalList:[],
    SumPrice:0 // 购物车总价格
}
const mutations={
    PUSH_ITEM(state,item){
        state.List.push(item);
        state.SumPrice+=item.price;
    },
    REDUCT_ITEM(state,item){
        let index = state.List.findIndex(i=>i.id==item.id);
        state.List.splice(index,1);
        state.SumPrice-=item.price;
    }
}
const actions={
    ADD_TO_CARD({commit},cartItem){
        return api.Insert(cartItem).then(res=>{
            if(res){
                return 'OK';
            }
        }).catch(err=>{
            return err;
        })
    },
    //获取查询对象 这个方法一定要在vue模块中先执行。‘
    GET_CART_BY_USERID({commit,state},uid){
        state.List = [];
        state.SumPrice = 0;
        api.Select().then(res=>{
            for(let item of res.data){
                if(item.userInfo == uid){
                    commit('PUSH_ITEM',item)
                }
            }
        })
    },
    DELETE_ITEM({commit},cartItem){
        api.Delete(cartItem.id).then(res=>{
            console.log(res.data);
            commit('REDUCT_ITEM',cartItem);
        })
    }
}
const getters={
    CAST_LIST(state){
        return state.List;
    }
}

export default {
    state,mutations,actions,getters
}

个人对Vuex四大核心的认识,state是存放数据的地方,而actions是异步操作干的事情,而异步操作对掠夺略少都有对数据的操作,这个时候就要用到mutations,它在其中对数据进行了操作,那么在定义actions的时候,方法上的参数一定要有commit,它是对数据进行回滚的,而mutations中的方法一定要state,它肯定是对数据进行操作的;getters的能力就是公开属性,它常用于vue模块中计算属性的配合使用(computed).

相关