配置vuex
编写vuex子模块
import { getInvoiceByCompanyId } from "@/api/stoneTax";
export const state = {
theInvoiceGoods: [],
};
const getters = {};
const mutations = {
//设置发票品类
setTheInvoiceGoods(state, { data }) {
state["theInvoiceGoods"] = data;
},
reset: () => {},
};
const actions = {
//载入测评报告信息
async loadInvoiceByCompanyId(
{ commit, rootState },
{ $http, companyId, month }
) {
try {
const resData = await getInvoiceByCompanyId($http, {
companyId,
month,
});
commit("setTheInvoiceGoods", { data: resData.data });
} catch (error) {
throw error;
}
},
};
export default {
namespaced: true,
state,
actions,
getters,
mutations,
};
引入子模块到store
store/index.js
import Vue from "vue";
import Vuex from "vuex";
import { state, mutations, actions } from "./store";
import createCache from "vuex-cache";
import VuexReset from "@ianwalter/vuex-reset";
import UploadTable from "@/pages/Test/UploadTable/store";
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== "production";
export default new Vuex.Store({
modules: {
UploadTable
},
state,
mutations,
actions,
strict: debug,
plugins: [createCache(), VuexReset()]
});
引入vuex到vue
main.js
import store from "./store";
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
组件中访问vuex
import { mapMutations, mapActions, mapGetters, mapState } from "vuex";
export default {
methods: {
...mapMutations("moduleName", ["setTheInvoiceGoods"]),
...mapActions("moduleName", ["loadInvoiceByCompanyId"]),
},
computed: {
...mapGetters("moduleName", ["isEditableForAction"]),
...mapState("moduleName", ["theInvoiceGoods"]),
},
};