7

When using vuex mapState, the documentation says you can use spread syntax as below, which I have working as intended.

I'm just curious as to what this is actually doing, so I have a better understanding of using spread syntax.

Would this...

computed: {
  ...mapState([
    'message',
    'storeArray'
  ])
}

Be effectively doing this... ?

computed: {
  message(){
    return this.$store.state.message
  }
  storeArray(){
    return this.$store.state.storeArray
  }
}

3 Answers 3

7

Yes.

What mapState does is returning an object with the functions, so effectively it is returning

{ 
  message(){
    return this.$store.state.message
  }
  storeArray(){
    return this.$store.state.storeArray
  }
}

or actually

{ 
  message: function(){
    return this.$store.state.message
  }
  storeArray: function(){
    return this.$store.state.storeArray
  }
}

which is the same thing.

What the spread operator does is extracting the objects keys and puts them into the parent object, replacing any already existing keys with the same name.

So it's basically the same as doing:

computed: {
  message: mapState(['message','storeArray'])['message'],
  storeArray: mapState(['message','storeArray'])['storeArray']
}

You can think of the spread operator as an easier way of using Object.assign.

computed: {...mapState(...), ...myOtherComputedObject)
computed: Object.assign({}, mapState(...), myOtherComputedObject)
Sign up to request clarification or add additional context in comments.

Comments

3

Like they say in official doc :

Note that mapState returns an object. How do we use it in combination with other local computed properties? Normally, we'd have to use a utility to merge multiple objects into one so that we can pass the final object to computed. However with the object spread operator (which is a stage-4 ECMAScript proposal), we can greatly simplify the syntax:

 computed: {
    localComputed () { /* ... */ },
    // mix this into the outer object with the object spread operator
    ...mapState({
      // ...
    })
  }

this syntax is used to simplify and provide a clean code and also it is necessary when you're using locale computed properties

1 Comment

This helped. It wasn't clear from the docs that the 3 dots do represent the actual operator.
1

Yes. This discussion is relevant.

While effective, using Object.assign() can quickly make simple reducers difficult to read given its rather verbose syntax.

An alternative approach is to use the object spread syntax recently added to the JavaScript specification. It lets you use the spread (...) operator to copy enumerable properties from one object to another in a more succinct way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.