vuex分了多个模块,利用语法糖调用不同模块里的方法

// store/modules/a.js
export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}
 
// store/modules/b.js
export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}
 
// store/index.js
import Vuex from 'vuex';
import A from './modules/a';
import B from './modules/b';
 
const store = new Vuex.Store({
  modules: {
    a: A,
    b: B
  }
});
 
export default store;

  

//vue页面
<script> import { mapState, mapMutations, mapActions } from 'vuex'; export default { computed: { // 使用mapState生成计算属性 ...mapState({ countA: state => state.a.count, // 从a模块获取状态 countB: state => state.b.count, // 从b模块获取状态 }), }, methods: {
    //使用mapMutations生成方法(只用到了一个方法,多个方法可参考mapActions的写法)
    ...mapMutations('a', {
      update: 'updateValue' // 假设模块a中的mutation名为updateValue
    }), // 使用mapActions生成方法 ...mapActions({ incrementA: 'a/increment', // 从a模块调用action incrementB: 'b/increment', // 从b模块调用action }),
   someMethod(){
    this.update(newValue); // 调用模块a中的mutation
   }
  },
};
</script>

  

posted @ 2024-04-08 18:31  90一代  阅读(47)  评论(0编辑  收藏  举报