Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three periods syntax in Vuex?

Tags:

vuex

I'm not solid on what mapstate does, other than that, what would ... mean in front of it. I don't see this nowhere as much within the guide as in example repos.

computed: {
  ...mapState({
    messages: state => state.messages
  })
}
like image 482
janat08 Avatar asked Oct 04 '16 14:10

janat08


2 Answers

When you are building a large application by using Vuex,

you would have to manage your store in one place instead of separate them,

for example you have a large store and there's many states in the store:

const store =
{
    states: 
    {
        todo:
        {
             notes   : { ... },
             username: { ... },
             nickname: { ... }
        },
        checklist:
        {
             list: { ... }
        }
    } 
}

if you want to use them, you could just do this

computed:
{
    ...mapState(['todo', 'checklist'])
}

so you don't have to

computed:
{
    todo()
    {
        return this.$store.state.todo
    },
    checklist()
    {
        return this.$store.state.checklist
    }
}

and then use them like this:

todo.notes
todo.usernames
checklist.list
like image 109
Yami Odymel Avatar answered Oct 10 '22 07:10

Yami Odymel


As @Can Rau had answered, I will try to make more clear about what the h3ll is Spread Syntax ... actually do in mapGetter, mapState and mapActions in Vuex.

Firstly, You can use directly mapState as: computed: mapState without Spread Syntax ... when you don't have any local computed properties.

The same with mapGetters and mapActions


computed: mapState({
    count: state => state.count,
    },

computed: {
  ...mapState({
     count: state => state.count,
  })
}

Both of the above do exactly the same thing!

But when you do have any local computed property, then you need Spread Syntax.

It because the mapState returns an object. And then we need Object Spread Operator to merge multiple Objects into one.

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

You can read more about Spread in object literals in MDN

Basically, in this situation, it used to merge objects

let obj = {a: 1, b: 2, c: 3}
let copy = {...obj}
// copy is {a: 1, b: 2, c: 3}

//without ..., it will become wrong
let wrongCopy = {obj}
// wrongCopy is { {a: 1, b: 2, c: 3} } - not what you want

And the Vuex Docs explains this quite clear. Take a look more deeply and you will get the idea.

like image 37
Thinh NV Avatar answered Oct 10 '22 06:10

Thinh NV