Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch deep array using computed in Vuejs

I made a component like below in Vuejs.
But my goal is I want to get the value inside of filterdShoes of watch.

   data():{
       coor: [
              { "name": '',
                "shoes": '' },
              { "name": '',
                "shoes": '' }       
             ]
   },

   computed {
      filteredAny(){
        return this.coor.filter(it=>['shoes','name'].includes(it));
      },
      filteredShoes(){
        return this.coor.filter(it=>it === 'shoes');
      },
     filteredName(){
        return this.coor.filter(it=>it === 'name');
      }

    }

    watch {
      filteredShoes(){
        console.log('The shoes are changed');
      }

    }

So I tried like below.But it says val is undefined.
I hope that 'val' is defined as 'coor' of data.
How can I fix this code? Thank you so much for reading this.

 watch {
      filteredShoes(val){  
        for(let i=0; i < val.length; i+=1){} 
      }

    }
like image 570
DD DD Avatar asked Oct 15 '22 11:10

DD DD


1 Answers

Since this.coor is an array of objects, it will be an object. Thus it != 'shoes', and your filter will return an empty array.

Assuming you are using computed filteredShoes() like this:

<div v-for="shoe in filteredShoes"> ... </div>

Then you can just use the computed property, no need for the watcher. Everytime elements are added to/removed from the array, the computed prop will run. The computed property will not run if the properties of an object in the array are changed.

Also, I'm not quite sure why your this.coor has such a structure, so I'm using this:

coor: [
   { "name": 'Model 1', "shoes": 'Nike' },
   { "name": 'Model 2', "shoes": 'Reebok' }       
]
...
computed {
   filteredShoes(){
      let shoes = this.coor.filter(item => item.shoes === 'Nike');

      for(let i = 0; i < shoes.length; i++){ ... } // assuming you're modifying each object here

      return shoes; // return an array to be looped in HTML
   },
}

If you're trying to filter by type, I would recommend changing your coor to the following structure:

coor: [
   { "name": 'Model 1', "type": 'shoe' },
   { "name": 'Model 2', "type": 'shoe' }       
]
...
computed {
   filteredShoes(){
      let shoes = this.coor.filter(item => item.type === 'shoe');

      ...
      return shoes; // return an array to be looped in HTML
   },
}
like image 78
Pei Qi Tea Avatar answered Oct 17 '22 23:10

Pei Qi Tea