vuex 使用文档小结篇

2020-06-16 05:41:34易采站长站整理

      使用常量替代 Mutation 事件类型

      使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式     


export const SOME_MUTATION = 'SOME_MUTATION';
      import Vuex from 'vuex'
      import {SOME_MUTATION } from './mutation-types'
      const store = new Vuex.Store({
          state: {...}
          mutations: {
            // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
            [SOME_MUTATION] (state) {
            // mutate state
            }
          }
      })

mutation 必须是同步函数

    一条重要的原则是记住 mutation 必须是同步函数。       


 mutations: {
          someMutation (state) {
            api.callAsyncMethod(() => {
                state.count++
            })
          }
        }

 在组件中提交 Mutations

    你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使使用 mapMutations辅助函数将组建中的methods 映射为 store.commit 调用 (需要在根节点注入 store)    


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

Actions  

    在mutation 中混异步调用会导致你的程序很难调试。

Actions

    Action 类似于 mutation,不同在于。

    Action 提交的是 mutation ,而不是直接变更状态。

    Action 可以包含任意异步操作。

    注册一个简单的 action    


const store = new Vuex.Store({
      state: {
          count:0