Mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。(官方希望我们使用mutation的方式去修改state)

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

组件中调用 vuex 中的 mutation

store.commit('increment')

携带参数

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

唔。。。这里官方希望你传参使用对象的形式

 

 这里是风格问题

嗯~ o(* ̄▽ ̄*)o,接着这里官方介绍了 对象风格的提交方式

 

 当使用对象风格的提交方式,整个对象都作为载荷(参数)传给 mutation 函数,因此 handler(函数方法) 保持不变:

 

 


 

Mutation 需遵守 Vue 的响应规则

既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

  1. 最好提前在你的 store 中初始化好所有所需属性。

  2. 当需要在对象上添加新属性时,你应该

  • 使用 Vue.set(obj, 'newProp', 123), 或者

  • 以新对象替换老对象。例如,利用对象展开运算符 (opens new window)我们可以这样写:

state.obj = { ...state.obj, newProp: 123 }

注意了:2、这里的目的是,state的添加,先不要懵逼

 

Mutation 必须是同步函数

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

现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。

这里同步的意思应该是,同步异步的意思吧,就是说这方法是同步的,不懂的去百度一下,拒绝懵逼,下面继续

mapMutation

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

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

 

为了不就此懵逼,在此自我总结一下

  state: {
    count: 0
  },
  mutations: {
    add (state, val = 1) {
      state.count++
      console.log(val)
    }
  }

 

<template>
  <div id="app">
    {{count}}
    <!-- 负荷传值 -->
    <button @click="add(1)">myMUTation</button>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  computed: {
    // 使用对象展开运算符将此对象混入到外部对象中
    ...mapState({ count: 'count' })
  },
  methods: {
    // mytest () {// 第一种方式 提交的形式
    //   this.$store.commit('add')
    // },
    ...mapMutations({ //第二种方式 使用辅助函数
      add: 'add' // 支持载荷(参数)
    }),
  ...mapMutations([ //第二种方式 使用辅助函数
     'add' // 支持载荷(参数)
    ])
} } </script>

 

posted on 2020-12-21 16:21  京鸿一瞥  阅读(288)  评论(0)    收藏  举报