Vuex之Mutation

更改 Vuex store 中的 state 的唯一方法是 commit mutation

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    //接受state作为第一个参数
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

使用方法:

store.commit('increment')

提交载荷(Payload)

可以向 store.commit 传入额外的参数,即 mutation载荷(payload)

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

在大多数情况下,载荷应该是一个对象:

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

对象风格的提交方式

store.commit({
  type: 'increment',
  amount: 10
})

Mutation 需遵守 Vue 的响应规则

1、最好提前在 store 中初始化好所有所需属性;
2、当需要添加新属性时,应该:
-使用 Vue.set(obj, 'newProp', 123)
-使用新对象替换老对象,如使用对象展开运算符可以写成:

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

使用常量替代 Mutation 事件类型

作用:可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
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

你可以在组件中使用 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')`
    })
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 7,985评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,296评论 0 6
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 4,005评论 0 3
  • State 单一状态树 Vuex使用单一状态树——用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据...
    oWSQo阅读 4,714评论 0 0
  • 1、工作抓狂,换工作可行吗? 参加工作多年,也算是职场老鸟了,工作中大事小事杂事琐事纷纷扰扰,令人心力憔悴、力不从...
    徐行洲阅读 5,590评论 16 10