Vuex:为什么我们要用大写字母编写 mutations、actions 和 getters?

Vuex: Why do we write mutations, actions and getters in uppercase?

我想知道为什么我们要用大写字母写mutations、actions和getters的函数名?这个约定从何而来?

export default {
  SOME_MUTATION (state, payload) {

  },

  ANOTHER_MUTATION (state, payload) {

  },
}

常量全部大写是long standing coding style

来自 Vuex documentation:

It is a commonly seen pattern to use constants for mutation types in various Flux implementations. This allows the code to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application

因此,它实际上只是遵循了在大多数情况下以大写字母命名常量的长期传统。不需要。

Whether to use constants is largely a preference - it can be helpful in large projects with many developers, but it's totally optional if you don't like them

Bert 接受的答案有点误导。常量变量传统上全部大写,但它在问题中的使用方式并没有使它成为常量。

This allows the code to take advantage of tooling like linters

官方 Vue.js 文档 recommends using all caps,但作为附加文件中的变量。这使得需要其他文件中的可用函数名称并使用自动完成成为可能。

变异-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: {
    // we can use the ES2015 computed property name feature
    // to use a constant as the function name
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

请注意这里的不同写法(计算属性名称带方括号):

[SOME_MUTATION] (state) { }

如果你只是把函数名全部写成大写(即 SOME_MUTATION(state) { })唯一的好处是视觉上的,将 vuex 函数与其他函数区分开来,但在我看来这没有多大意义.坚持使用计算出的 属性 名称 ([SOME_MUTATION] (state)) 以获得所有好处。