softcode
softcode

Reputation: 4668

Vue.js Spread Operator instead of Vue.set / Vue.delete

I would like to use the spread operator to add/remove object properties while maintaining reactivity.

In a Vuex mutation, the following works:

Vue.set(state.sportTypes.sports, sportName, sportProperties)

However I would like to use the spread operator and return new object. How would I achieve the following?

state.sportTypes.sports = {...state.sportTypes.sports, {sportName: sportProperties}}

Upvotes: 1

Views: 2430

Answers (1)

CodinCat
CodinCat

Reputation: 15914

You should remove the brackets of {sportName: sportProperties}

This will work:

state.sportTypes.sports = { ...state.sportTypes.sports, sportName: 'football' }

But I'd recommend you to declare all the possible fields, instead of add new attributes dynamically, then you don't need to use Vue.set nor the spread operator.

Upvotes: 1

Related Questions