user6806370
user6806370

Reputation:

Clarification re: Vue.js actions/mutations

I need some clarification re: the interplay between these functions. I'm following a Vue.js tutorial and we have an action that commits a mutation.

Action:

updateUser({commit}, user) {
  commit('setUser', {userId: user['.key'], user})
}

Mutation:

setUser(state, {user, userId}) {
  Vue.set(state.users, userId, user)
}

My question is about the order of arguments in the commit() call in the action. The payload is an object with a userId as its first name-value pair, and its second value is the user object itself. Now, in the mutation definition, the values in the payload the mutation is expecting are reversed. I can't imagine how JavaScript/Vue would know what types of data to expect in the setUser definition so that the order of the name-value pairs in the expected payload wouldn't matter. So why does the app still work? Is the mutation expecting to receive variables called user and userId, and that's why the order doesn't matter?

Upvotes: 0

Views: 18

Answers (1)

akuiper
akuiper

Reputation: 215117

It has nothing to do with Vue but a Javascript destructuring syntax; The order doesn't matter because it's extracting value from object by keys; in your case, setUser is expecting an object that contains a key user and a key userId which is passed down by the updateUser action; Also notice this is just a syntax sugar that you don't necessarily have to follow, that is, you can write your mutation that accepts a normal object as parameter as follows:

setUser(state, obj) {
  Vue.set(state.users, obj.userId, obj.user)
}

Upvotes: 1

Related Questions