twoam
twoam

Reputation: 892

How to update only one object with vue.set

I have an array with companies like this:

[{
    "id": 1,
    "firstname": "lorem",
    "lastname": "ipsum",
    "name": "something",
    "subscription": "premium",
    "active": 1
}]

The companies are displayed in a layout and when I click on one of them it triggers:

lockCompany(id, index) {
    Vue.set(this.companies, index, {active: 0});
}

But.. when I set active to 0 it removes firstname etc.. Am I doing something wrong?

Upvotes: 0

Views: 2431

Answers (2)

Djave
Djave

Reputation: 9329

You are setting the item in the companies array at a position of 0 to { active : 0 }

You probably just want to do

lockCompany(id, index) {
    Vue.set(this.companies[index], 'active', 0 );
}

That will just set the active property to 0 instead.

Upvotes: 1

raina77ow
raina77ow

Reputation: 106385

Should be either (if you properly use :key=item.id in your v-for template):

Vue.set(this.companies[index], 'active', 0);

... or (otherwise):

let newCompany = Object.assign({}, this.companies[index], { active: 0 });
Vue.set(this.companies, index, newCompany);

As it stands, you just rewrite an element of your array with completely new object each time Vue.set is called.

Upvotes: 2

Related Questions