Narutocc / Vue

:smirk_cat:Vue is a progressive framework for building user interfaces. Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
1 stars 0 forks source link

vuex——mapMutations #26

Open Narutocc opened 6 years ago

Narutocc commented 6 years ago

mutations

更改状态的唯一方法是提交变异,意思就是在mutation的方法中更改state,然后通过store.commit()去触发编写的方法,从而达到更改了state。例子如下:

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

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

使用常量进行变异类型 Mutation Types

即:将所有常量放在一个文件中,可以一目了然地查看整个应用程序中可能发生的突变。是否使用常量在很大程度上是一种偏好,它对于许多开发人员的大型项目很有帮助。当然,这种编写是可选的。 如下:

// 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: {
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

提交组件中的mutation

可以在组件中提交mutation this.$store.commit('xxx'),或使用mapMutations将组件方法映射到 store.commit(需要根store注入)

// 某组件
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations([
      'increment', // map`this.increment()` to `this.$store.commit('increment')`
      'incrementBy' // map`this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
    ])
    ...mapMutations({
      add: 'increment' // map`this.add()` to `this.$store.commit('increment')`
    })
  }
}