vuex--辅助函数mapState,mapGetters, mapActions, mapMutations

  • 以mapActions为例,通常,我们在vuex的actions中定义一个方法:
export default {
    vuexSetUserLogin({commit}){
        commit("vuex_set_user_login");
    },
    vuexSetTest({commit}, val){
        commit("vuex_set_test", val);
    }
}

调用时这样调用:

this.$store.dispatch("vuexSetTest", "ttttttt");
  • mapActions的作用就是,把actions中的方法映射到methods中,换一种调用方式。
    引入mapAction:
import {mapActions,} from 'vuex'

映射方法:

"methods": {
    ...mapActions([
        "vuexSetUserLogin",
        "vuexSetTest"
    ]),
},

把actions里面的两个方法映射到本地的同名方法
调用的时候就像调用本组件的method一样:

this.vuexSetTest("eeee");
  • mapActions() 返回的是一个对象, 用了 ... 扩展符后,才可以放进一个对象里,和其他组件内定义的 method 在同一个 methods 对象。
{
    methods: mapActions() // 如果没有其它组件内的定义的方法,可以这样写
}
{
    methods: {
        ...mapActions(),// 如果有其他定义的方法
        otherMethod1 () {},
        otherMethod2 () {}
    }
}
  • mapGetters:
computed:mapGetters([
 'count'
 ]),
  • 映射的时候可以取别名:
export default {
  // ...
  methods: {
       //下述中的 ... 是拓展运算符
       // 使用 [] 是解构赋值
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
 
      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容