天天看点

vuex的语法糖-辅助函数mapState , mapMutations , mapActions , mapGetters

还不知道vue中vuex如何使用?点击下面链接

链接:简单demo详细讲解

复习vuex工作原理

vuex五大核心

1.State

2.Getters

3.Mutations

4.Actions

5.Module

我们项目中需要的都是:state、getters、mutations、actions里面的东西

调用方法和使用的位置也是有区别的分别是

不过vuex给我们提供了辅助函数:mapState , mapMutations , mapActions , mapGetters

调用 方法 辅助函数
state this.$store.state. xxx mapState
getters this.$store.getters. xxx mapGetters
mutations this.$store.cmmit((xxx) mapMutations
actions this.$store.dispatch(xxx ) mapActions

注意

mapState和mapGetter的使用只能在computed计算属性中,

mapMutations和mapActions使用的时候只能在methods中调用否则报错

如何实际使用辅助函数?

<script>
import { mapState , mapMutations , mapActions , mapGetters  } from 'vuex';
export default {
  data(){
    return{

    }
  },
  computed:{
    ...mapState({
      counts:(state) => state.count
    }),
    //mapState就等于下面这个
    // counts(){
    //   return this.$store.state.count
    // },
    ...mapGetters({
      getternum:'doneTodos'
    }),
    //mapGetters就等于下面的这个
    // getternum(){
    //   return this.$store.getters.doneTodos
    // }

  },
  methods:{
    ...mapMutations({
      addnum:'addNum'
    }),
    addnum1(){
      this.addnum()
    },
    //mapMutations就等于下面的这个
    // addnum1(){
    //   this.$store.commit('addNum')
    // },
    
    ...mapActions({
      actionnum:'actionNumAdd'
    }),
    actionnum6(){
      this.actionnum()
    },
    //mapActions就等于下面的这个
    //  actionnum6(){
    //   this.$store.dispatch('actionNumAdd')
    // }
    
  }
}
</script>
           

辅助函数总结

vuex中的 mapState , mapMutations , mapActions , mapGetters 辅助函数

看上面的例子其实差不多,

当项目场景中我们需要大量的调用state中的值和触发多个actions的时候,我们还得写大量重复的代码,这时候辅助函数的作用就体现出来了,其实就是vuex的一个语法糖,是代码更简洁更优雅。

不想复制粘贴的直接去github:https://github.com/babybrotherzb/vue2-vuex