5

I wonder why mutation values ​​are used in "[]" in Vuex.

What does the code like "" mean?

export const SOME_MUTATION = 'SOME_MUTATION'

Is it just a constant name for the function? If so, I wonder why the constant is written in "[]".

Also, when used in the computed or method property, I wonder why you would pass the following code as ["SOME_ACTION"] instead of "SOME_ACTION".

...mapActions(["SOME_ACTION"]),

exam code

export const SOME_MUTATION = 'SOME_MUTATION'

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

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    [SOME_MUTATION] (state) {
    }
  }
})
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
dsfdsf2fafad
  • 321
  • 2
  • 12
  • It's a computed property name (really a method). So `mutations` is an object that has a method named the value of `SOME_MUTATION`, which is just `'SOME_MUTATION'` – Andrew Li Jun 12 '19 at 00:56
  • Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – Phil Jun 12 '19 at 02:47

1 Answers1

5

It is called a computed property name. It is not a Vuex thing. It's a ECMAScript 2015 thing. So any engine that supports ES2015 will support that syntax.

Before ES2015, object property names cannot be computed. Meaning if you want to have a dynamic property name, you'll probably write something like:

const obj = {};
const result = Math.random() < 0.5;

if (result)
  obj.data = result;
else
  obj.error = result;
  
console.log(obj);

Using ES2015 computed property, you can now do something like:

const result = Math.random() < 0.5;
const SOME_PROPERTY = result ? 'data' : 'error';

const obj = {
  [SOME_PROPERTY]: result
}

console.log(obj);

Of course this is just a very simplified example and doesn't really demonstrate what benefit it brings, but it's a really good syntax suger in my opinion.

You can find more about its use case online.

yqlim
  • 6,898
  • 3
  • 19
  • 43