Vuex

1 、辅助函数
 
  • mapState

 ...mapState({
    a: state => state.some.nested.module.a, b: state => state.some.nested.module.b })

简写带空间名称的字符串html

 
 
...mapState('some/nested/module', {
    a: state => state.a, b: state => state.b })
  • mapActions

  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    selfDefine:'some/nested/module/  bar' // -> this['some/nested/module/bar']()
  ])

简写带空间名称的字符串vue

 ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])

 

建立基于命名空间的组件绑定辅助函数。其返回一个包含 mapState、mapGetters、mapActions 和 mapMutations 的对象。它们都已经绑定在了给定的命名空间上。
 
更好的写法:
 1 import { createNamespacedHelpers } from 'vuex'
 2 
 3 const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
 4 
 5 export default {
 6   computed: {
 7     // 在 `some/nested/module` 中查找
 8     ...mapState({
 9       a: state => state.a,
10       b: state => state.b
11     })
12   },
13   methods: {
14     // 在 `some/nested/module` 中查找
15     ...mapActions([
16       'foo',
17       'bar'
18     ])
19   }
20 }

 

action 经过  store.dispatch 方法进行分发:
 
乍一眼看上去感受画蛇添足,咱们直接分发 mutation 岂不更方便?实际上并不是如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!咱们能够在 action 内部执行异步操做:
 
 
 mutation 必须同步执行这个限制么?Action 就不受约束!咱们能够在 action 内部执行异步操做:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
 
Actions 支持一样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发
store.dispatch({ type: 'incrementAsync', amount: 10 })

在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(须要先在根节点注入 store):vuex

import { mapActions } from 'vuex' 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')`
 }) } }
 commit 和 dispatch的区别 = 一个异步操做与同步操做的区别。

当你的操做行为中含有异步操做,好比向后台发送请求获取数据,就须要使用action的dispatch去完成了。其余使用commit便可。异步

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息