0

Found this in a tutorial I was going over. It's ES6.

I'm just not sure whats exactly going on. Namely , the way the function(?) is being declared with the array. Where is the colon that declares it as a function?

[types.ADD_TO_CART] (state, { id }) 

Also what's up with the brackets in the parameter declaration?

(state, { id })

Here's the tutorial.

https://medium.com/@connorleech/build-a-shopping-cart-with-vue-2-and-vuex-5d58b93c513f

[types.ADD_TO_CART] (state, { id }) {
  const record = state.added.find(p => p.id === id)
  if (!record) {
    state.added.push({
      id,
      quantity: 1
    })
  } else {
    record.quantity++
  }
}
nem035
  • 31,501
  • 5
  • 73
  • 88
mutant_city
  • 1,783
  • 21
  • 38

2 Answers2

3

You must define a method on a class without using ::

class Example {
  method() {
    console.log('here')
  }
}

new Example().method()

With ES6 computed property names, you can make the name of that method be dynamic:

const name = 'method'
class Example {
  [name]() {
    console.log('here');
  }
}

new Example()[name]()

As far as the ({ id }) part, the id represents an extracted property from the arguments of that dynamic method using destructuring:

// this
[types.ADD_TO_CART](state, obj) => {
   let id = obj.id;
}

// can be abbreviated to this
[types.ADD_TO_CART](state, { id }) => {

}

For example:

const name = 'method'
class Example {
  [name]({
    id
  }) {
    console.log(id);
  }
}

new Example()[name]({
  id: 'example'
})

Further resources: this one and this one and this one

nem035
  • 31,501
  • 5
  • 73
  • 88
1

With ES2015, you can get two new features for object literals:

// Computed object properties

const foo = 'bar'
const myObj = {
    [foo]: 'hello world'
}

// Shorthand method definitions:

const mySecondObj = {
    myMethod () {
        // code...
    }
}

The code in the example seems to combine both.


Also, ES2015 gives you object destructuring, which is used for the parameter – thus the curly brackets.


Check MDN for more details on the new syntax features.

TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86