module
由於購物車與商品各自有許多不同的函數,為了未來維護上方便,我們將其拆成獨立的檔案,這樣在 store 中就不會一次出現很長一串的程式碼,這裡我們以 products 來做範例。
products
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import shop from "../../api/shop";
import * as types from "../mutation-types";
const state = { all: [] };
const getters = { allProducts: state => state.all };
const actions = { getAllProducts({ commit }) { shop.getProducts(products => { commit(types.RECEIVE_PRODUCTS, { products }); }); } };
const mutations = { [types.RECEIVE_PRODUCTS](state, { products }) { state.all = products; },
[types.ADD_TO_CART](state, { id }) { state.all.find(p => p.id === id).inventory--; } };
export default { state, getters, actions, mutations };
|
引用
模組設定好之後,我們只要在 store 的 modules 引用,就可以使用了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import Vue from "vue"; import Vuex from "vuex";
import * as actions from "./actions"; import * as getters from "./getters"; import cart from "./modules/cart"; import products from "./modules/products"; import createLogger from "../../../src/plugins/logger";
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== "production";
export default new Vuex.Store({ actions, getters, modules: { cart, products }, strict: debug, plugins: debug ? [createLogger()] : [] });
|