vuex-Mutation(同步)

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation.Vuex 中的 mutation 非常类似于事件

每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

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

//提交motations:
store.commit('increment')

//
向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
store.commit('increment', { amount: 10 })

//对象风格的提交方式
store.commit({ type: 'increment', amount: 10 })

 

Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项

1,提前在你的 store 中初始化好所有所需属性
2,在对象上添加新属性
    Vue.set(obj, 'newProp', 123)
    //新对象替换方式
    state.obj = { ...state.obj, newProp: 123 }

//mutation必须是同步函数
//任何在回调函数中进行的状态的改变都是不可追踪的。

 

使用常量作为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

//可以用this.$store.commit("***");
//可以用mapMutations将组件中的 methods 映射为 store.commit 调用

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')` }) } }

 

转载于:https://www.cnblogs.com/avidya/p/8432458.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值