Home » vue » Know when DOM element has changed in Vue.js

Know when DOM element has changed in Vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am looking to figure out when a particular DOM element has been changed due to the vue data being updated.

So in the example below, I want to know when {person.favoriteColor} changes. person.favoriteColor is part of a dynamic list of people and at any point, that person can change their favorite color. The number of people can also change at any time. So for this need, I am really only looking to know when that particular person’s favorite color has been updated.

<div v-for="person in people">
    <div>{{person.favoriteColor}}</div>
</div>

An idea of what I need:

<div v-for="(person, index) in people">
    <div v-on:update='thisHasBeenUpdated(index)'>{{person.favoriteColor}}</div>
</div>
Answers:

It sounds like you want to use watch:

watch: {
  'person.favoriteColor': {
    handler(value, oldValue) {
      console.log(`Favorite color changed from ${oldValue} to ${value}`);
    }
  }
}