Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mapGetters、mapMutations、mapActions用法 #2

Open
lensh opened this issue Jul 23, 2017 · 0 comments
Open

mapGetters、mapMutations、mapActions用法 #2

lensh opened this issue Jul 23, 2017 · 0 comments

Comments

@lensh
Copy link
Owner

lensh commented Jul 23, 2017

首先得通过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')
    })
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant