Nacim Idjakirene
Nacim Idjakirene

Reputation: 1931

Vue js 2 : How to filter array without mutation?

I have a very simple Laravel /Vue js website, I have a list of product which I would like to filter.

const app = new Vue({
el: '#main-content',
data: {
    forfaits: window.forfaits,
},
methods: {
   filterData: function (val) {
        console.log(val)
        this.forfaits = this.forfaits.filter(item => {
          return item.internet >=val[0] && item.internet <= val[1] ;
      });
      return this.forfaits;
      
  }

HTML

 <div class="product-item offre" v-for="forfait in forfaits">
 .....
 ..... 
 .....

In this case it works but the original product array (forfaits) is mutated. How can I filter without mutating the original value?

Upvotes: 1

Views: 839

Answers (1)

SLaks
SLaks

Reputation: 887453

You want to have two properties:

  1. A source-of-truth property with all unfiltered items, which is never consumed by the UI.
  2. A computer property with the actual list to display, which at any point will return the complete list if there is no filter, or a filtered list if there is a filter. This is what you bind the UI to.

You don't need any methods; the computed property will automatically update as the filter changes.

Upvotes: 4

Related Questions