0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Quick question, why do I need :key=id for? Right now I get the index with v-for="(company, index) in companiesCheck" Should I change this?
Not sure what companiesCheck is (it's not shown in your example), but yes, usually using :key is an optimal strategy. Check this section of official documentation for details.
I can't seem to get it working.. I've changed the key to v-for="company in companiesCheck" :key="company.id" and trigger the function with @click="lockCompany(company.id)" and changed vue set to Vue.set(this.companiesCheck[id], 'active', 0); But I get a error: Cannot use 'in' operator to search for 'active' in undefined
You seem to confuse id and index here. Instead of passing company.id so that you have to look up for specific element in an array, just pass company as a whole instead, then update it. Like this: lockCompany(company);, and then Vue.set(company, 'active', 0).
Thank you! I tried deleting a company with vue.delete but with no success. Now I use Vue.delete( this.companies, index );. If you know a better solution I would love to hear:)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.