天天看點

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