Vuex: what is mean square bracket in mutation?

Viewed 1904

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) {
    }
  }
})
1 Answers

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.

Related