store下的index.js文件
//引入Vuex -----相当于咱们最大的仓库
import Vuex from "vuex";
//引入Vue
import Vue from "vue";
//使用插件
Vue.use(Vuex);
//引入home|search模块的仓库
import home from "./home";
//需要暴露Vuex.Store类的实例(你需要暴露这个类的实例,如果你不对外暴露,外部是不能使用的)
export default new Vuex.Store({
//模块:把小仓库进行合并变为大仓库
modules: {
home,
},
});
store下的home.js文件
import { reqgetCategoryList } from "@/api";
//home模块的仓库
const state = {
//home仓库中存储三级菜单的数据
categoryList: [],
};
//mutions是唯一修改state的地方
const mutations = {
GETCATEGORYLIST(state, categoryList) {
state.categoryList = categoryList;
},
};
//action|用户处理派发action地方的,可以书写异步语句、自己逻辑地方
const actions = {
async getCategoryList({ commit }) {
//reqgetCategoryList返回的是一个Promise对象
//需要用await接受成功返回的结果,await必须要结合async一起使用(CP)
let result = await reqgetCategoryList();
if (result.code == 200) {
commit("GETCATEGORYLIST", result.data);
}
},
},
};
//计算属性
const getters = {};
export default {
state,
mutations,
actions,
getters,
};
使用store数据页面
import { mapState } from "vuex";
...mapState({
categoryList: (state) => state.home.categoryList,
}),
this.$store.dispatch("getCategoryList");