Vuex: Add property to object in vuex

Created on 25 Jul 2016  路  11Comments  路  Source: vuejs/vuex

Hi,
I am trying to add property to object stored in vuex here is the code

[SET_PROJECT_GROUPS] (state, project, groups) {
    let projectIndex = state.all.indexOf(project);
    $set(state.all[projectIndex].groups, groups)
  },

What is the right way of doing this?

Most helpful comment

Use spread operator

state.obj = { ...state.obj, newProp: 123 }

https://vuex.vuejs.org/guide/mutations.html

All 11 comments

Vue's set signature is set(obj, key, val)

Already tried that and got
Uncaught (in promise) ReferenceError: set is not defined

@LinusBorg that link is dead now, can you explain. My guess is it's documented here now: https://vuex.vuejs.org/en/mutations.html

Please use forum.vuejs.org

use Vue.set();
or vm.$set()

Use spread operator

state.obj = { ...state.obj, newProp: 123 }

https://vuex.vuejs.org/guide/mutations.html

@LinusBorg Can you explain how Vue.$set work? Is that O(1)?

@mauriciopazpp thank you so so much!!!! It took many hours to get here.

state.obj = { ...state.obj, newProp: 123 }

If you need a dynamic prop name too, this works and preserves all my intended getters, setters, listeners, etc

let obj = {}
obj[dynamic] = value
state.obj = {...state.obj, ...obj}

This allowed me to add props to an empty state object and v-model to the new props.

@tarekadam A pretty common thing to do... props for your dynamic prop syntax.

Was this page helpful?
0 / 5 - 0 ratings