Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js spread syntax with Vuex

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
  }
}
like image 421
paddyfields Avatar asked Dec 24 '18 12:12

paddyfields


1 Answers

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)
like image 95
Jimmy Stenke Avatar answered Sep 30 '22 12:09

Jimmy Stenke