store.js
import Vue from "vue"; import Vuex from "vuex"; import { reqShopRatings } from "../api/index"; // 导入封装好的请求 Vue.use(Vuex); // 变量名 const EXAMPLE = "example"; // 定义数据 const state = { aaa:null, xxx:null }; // 同步 const mutations = { ccc(state,value){ state.aaa = value }, [EXAMPLE](state, { ratings }) { state.ratings = ratings; } }; // 异步 const actions = { async ddd({ commit }, value, callback) { const result = await reqShopRatings(); if (result.code === 0) { const ratings = result.data; commit(EXAMPLE, { ratings }); callback && callback(); } } }; // 计算属性 const getters = { bbb(state) { return 'act' // 必须要有返回值 } }; export default new Vuex.Store({ state, mutations, actions, getters });main.js
import store from './store' // 1.导入store new Vue({ el: '#app', render: h => h(App), store // 2.在vue注册 })使用
// 方法一 import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' computed: { ...mapState(['aaa', 'xxx']), ...mapGetters(['bbb']), }, computed: mapState({ companyList: state => state.drug.companyNameList, flag: state => state.echart.flag }), methods: { ...mapMutations(['ccc']), // 不能传参 ...mapActions(['ddd']), // 不能传参 } // 方法二 this.$store.state.aaa // state this.$store.getters.bbb // getters this.$store.commit('ccc', value) // mutitions this.$store.dispatch('ddd', value, ()=>{ // 页面更新后执行的函数(不需要不用) }) // actions