vuex之代码抽离

根据上篇文章的例子,进行代码抽离,
1、分别创建getters.js,mutations.js文件,并在store.js文件中引入

import * as mutations from "./mutations"
import * as getters from "./getters"

2、抽离之后的store.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as mutations from "./mutations"
import * as getters from "./getters"

Vue.use(Vuex)

export const store = new Vuex.Store({
    // 单一状态树 设置属性
    state:{
        // 商品数组
        goodsList:[]
    },
    // 获取属性
    getters,
    // 改变数据状态
    mutations
})

3、getters.js文件

// 获取商品列表
export const getterGoodsList = (state) =>{
    return state.goodsList;
}
// 获取所有商品的总价
export const getterGoodsTotalPrice = (state) => {
    var total = 0
    for (const key in state.goodsList) {
        if (state.goodsList.hasOwnProperty(key)) {
            const element = state.goodsList[key];
            total = total + parseFloat(element.total)
        }
    }
    return total
}

4、mutations.js文件

// 将新的商品添加到商品数组
export const addGoodsToGoodsList = (state,goods) => {
    state.goodsList.splice(0,0,goods);
}
 // 修改选中商品的数量
 export const changeGoodsCount = (state,payload) => {
    state.goodsList.forEach(element => {
        if (element.goodsId == payload.goodsId) {
            element.count = parseInt(element.count) + parseInt(payload.count);
            element.total = parseInt(element.count) * parseFloat(element.price);
        }
    })
}
// 根据商品id删除选中的商品
export const deleteGoodsToGoodsList = (state,item) =>{
   state.goodsList.splice(state.goodsList.indexOf(item),1)
}

具体代码详见:https://github.com/zzsuyifeng/vuexDemo/tree/separate

你可能感兴趣的:(vuex之代码抽离)