0

I have an array of objects in my state like so:

data() {
    return {
    users: [{id: 1, name: 'bob'}, {id: 2, name: 'bill'}]
    }
}

When I change the data like so:

this.users[0].name = 'Mary'

A watcher that I have for the students property does not run, how do I make it run?

2
  • 1
    First there is nothing called students in your question (code) and second, there is no watcher ...(at least in your question) Commented Apr 13, 2021 at 14:08
  • See Reactivity Change Detection Caveats Commented Apr 13, 2021 at 14:20

1 Answer 1

5

Vue.js cannot detect mutations to array when you change any item or sub-field of a item using direct index access.

To do this, you can use set method of Vue object:

// Vue.set
const index = 0;
const newValue = { ...this.users[index], name: 'Mary' };

Vue.set(this.users, index, newValue);

Or, you can simply use manipulate array using splice method which is internally over-riden by Vue.js:

const index = 0;
const newValue = { ...this.users[index], name: 'Mary' };

// Using array manipulation
this.users.splice(index, 1, newValue);

Or, you can use immutable data practice as:

const newArray = [...this.users];
const newValue = { ...this.users[0], name: 'Mary' };
newArray[0] = newValue;

this.users = newArray;
Sign up to request clarification or add additional context in comments.

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.