Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js watch a nested property inside array

I got a vue object like this:

var vm = new Vue({
            el: '#app',
            data: {
                items: [],
                index: 0
            },

            });

Inside items array i will push items like:

item1 = {
    a: 1,
    b: 'type',
    c: '3.556'
}
...
itemN = {
    a: n,
    b: 'type',
    c: '5.226'
}

then i will update one of the item's "c" property and i would like to set up a watcher that warn me as soon as one of this property changes.

EDIT: i also want to know witch item has changed

like image 403
Plastic Avatar asked Jan 08 '17 10:01

Plastic


People also ask

How do you watch for nested data changes?

We can watch for nested properties with watchers by adding methods to the watch property object with a property path. Also, we can set deep to true to watch for deeply nested properties.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

How do I watch an array in Vue?

You need to set deep to true when watching an array or object so that Vue knows that it should watch the nested data for changes. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.

How do I use watch property in Vue JS?

The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.


1 Answers

You can use deep watch, but... it does not provide ease way to determine which item has changed.

...
watch: {
  items: {
    handler: function (val, oldVal) {

    },
    deep: true
  }
}
...

One of possible workarounds is mentioned in this answer, idea behind this solution is to wrap each item in component and listen to event from component.

You can also store cloned items array and update that clone in watch handler, you can use that clone to filter item that has changed.

like image 77
donMateo Avatar answered Sep 29 '22 13:09

donMateo