lensh / vue-qq

🎨 Vue family bucket with socket.io and express/koa2 , create a web version of mobile QQ, supporting real-time group chat, real-time private chat, special care, shielding chat, smart IP geographic location, real-time display temperature and other QQ core functions
MIT License
917 stars 231 forks source link

mapGetters、mapMutations、mapActions用法 #2

Open lensh opened 7 years ago

lensh commented 7 years ago

首先得通过import从vuex里导入:

import { mapGetters,mapMutations,mapActions } from 'vuex' 1.mapGetters是将store的getters(getters可以认为是state的计算属性)自动映射到组件的局部计算属性里,在组件的计算属性里只需如下申明,就可以直接使用this.products来获取products了:

computed: {
    ...mapGetters({
      products: 'cartProducts',
      checkoutStatus: 'checkoutStatus'
    })
}

如果你要使用的计算属性名称刚好和getters初始的名称一致(即当键名和键值一样时),那么就可以写成数组的形式。

computed: {
    ...mapGetters([
      'products',   //注意这里一定要有引号,才会自动映射
      'checkoutStatus'
    })
}

原本需要使用this.$store.getters.products来获取products的,现在只需要使用this.products就可以了,是不是更简洁方便了呢? 2.mapMutations辅助函数是将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store),只需要在组件的methods里声明:

 methods: {
    ...mapMutations([
      'increment' // 映射 this.increment() 为 this.$store.commit('increment')
    ]),
    ...mapMutations({
      add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
    })
  }

这样我们就可以在组件里使用this.add()来替代 this.$store.commit('increment')了,又简短了不少。 如果需要传递参数,则可以直接在this.add(argument)里传参数argument 3.Action 类似于 mutation,不同在于: Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作。 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store), 使用方法如下:

  methods: {
    ...mapActions([
      'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
    ]),
    ...mapActions({
      add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
    })
  }