Search code examples
javascriptvue.jsecmascript-6vuejs2vuex

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
  }
}

Solution

  • 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)