Vux的基本模块化
目录:
1.在store文件夹下创建modules文件夹,modules文件夹下的index.js用来汇总Vuex的模块,并统一暴露。这样只需在store的配置中引入modules即可。
// 汇总所有vuex的模块
import home from "./home";
import login from "./login";
// 统一暴露出去
export default {
home,
login,
};
2.modules文件夹下,用来设置每个模块的状态管理配置。例如:
// home组件的vuex状态
export default {
state: {},
getters: {},
actions: {},
mutations: {},
};
3.在store的配置文件引入:
import modules from "./modules";
const store = new Vuex.Store({
state, // 总state
getters, // 总getters
actions, // 总actions
mutations, // 总mutations
modules, // 其他vuex模块的数据
})
4.组件中使用:注意点是:如果使用模块化在映射state时,接收使用对象,并且使用函数得到数据值,例如:
import { mapState, mapActions } from "vuex";
computed: {
// 当使用vuex模块化,这种方式就不行了
// ...mapState(["testCount", "categoryList"]),
// ...mapState(["testCount", "home"]), // 这种方式可以,需要使用 this.home.categoryList。太麻烦
...mapState({
// 对象中的数据,就会传递给组件
// categoryList就是组件能接受到的数据
// 它的值是一个函数,函数内部会调用得到值
// 调用时会将所有vuex数据传递进去,就是state
categoryList: (state) => state.home.categoryList
})
},
methods: {
// 函数直接写
// 注意:将来action函数名称和mutation函数名称不要重复
...mapActions(["getCategoryList"]),
},
mounted() {
// console.log(this);
// 直接使用this.调用vuex的action函数
this.getCategoryList();
}