在多人协作的大型项目中,将这些用于替代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: {    
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

注:ES6允许字面量定义对象时,用表达式作为对象的属性名和方法名,即把表达式放在方括号内。

在组件方法内提交mutation时,也要先导入常量:

import { SOME_MUTATION } from './mutation-types'

export default {
  methods: {
     this.$store.commit(SOME_MUTATION)
  }
}

但有个问题,在每个要提交mutation的组件中都要导入常量,会不会有点麻烦?


lavender
30 声望2 粉丝