vuex怎么模块化编码和命名空间

其他教程   发布日期:2023年06月11日   浏览次数:454

本文小编为大家详细介绍“vuex怎么模块化编码和命名空间”,内容详细,步骤清晰,细节处理妥当,希望这篇“vuex怎么模块化编码和命名空间”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

模块化编码+命名空间

小a:“为啥要开启这个捏?”山鱼:“当然是让代码更好维护,让多种数据分类更加明确。”

小a:“那如何才能做到模块化编码+命名空间呢”

山鱼:“只需要这样即可”

  1. // Count的相关配置
  2. export default {
  3. namespaced: true,
  4. actions: {
  5. // 奇数加法
  6. jiaodd(context, value) {
  7. if (context.state.sum % 2) {
  8. context.commit('JIA', value)
  9. }
  10. },
  11. // 延迟加
  12. jiaWait(context, value) {
  13. setTimeout(() => {
  14. context.commit("JIA", value)
  15. }, 500);
  16. },
  17. },
  18. mutations: {
  19. JIA(state, value) {
  20. state.sum += value
  21. },
  22. JIAN(state, value) {
  23. state.sum -= value
  24. },
  25. },
  26. state: {
  27. sum: 0, // 当前和
  28. school: '山鱼小学',
  29. subject: '前端',
  30. },
  31. getters: {
  32. bigSum(state) {
  33. return state.sum * 10
  34. }
  35. }
  36. }

2.开启命名空间后读取state的数据

  1. computed: {
  2. // 自己读取
  3. personList() {
  4. returnthis.$store.state.personAbout.personList;
  5. },
  6. sum() {
  7. returnthis.$store.state.countAbout.sum;
  8. },
  9. },
  10. // 借助mapState读取
  11. computed: {
  12. ...mapState("countAbout", ["sum", "subject", "school"]),
  13. ...mapState("personAbout", ["personList"])
  14. },

3.开启命名空间后,组件中读取getters数据

  1. computed: {
  2. // 自己读取
  3. firstName() {
  4. returnthis.$store.getters["personAbout/firstPersonName"];
  5. }
  6. },
  7. methods: {
  8. // 借助mapGetters读取
  9. // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
  10. ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式
  11. ...mapActions('countAbout',{ incrementOdd: "jiaodd", incrementWait: "jiaWait" }) //对象式
  12. },

4.开启命名空间后,组件中调用dispatch

  1. methods: {
  2. // 直接dispath
  3. addWang() {
  4. constpersonObj= { id: nanoid(), name: this.name };
  5. this.$store.dispatch("personAbout/addNameWang", personObj);
  6. this.name="";
  7. },
  8. },
  9. //借助mapGetters读取:
  10. computed: {
  11. ...mapGetters('countAbout',['bigSum'])
  12. },

5.开启命名空间后,组件中调用commit

  1. methods: {
  2. // 直接调用
  3. add() {
  4. constpersonObj= { id: nanoid(), name: this.name };
  5. this.$store.commit("personAbout/ADD_PERSON", personObj);
  6. this.name="";
  7. },
  8. }
  9. methods: {
  10. // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
  11. ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式
  12. },
  13. }

以上就是vuex怎么模块化编码和命名空间的详细内容,更多关于vuex怎么模块化编码和命名空间的资料请关注九品源码其它相关文章!