0
votes

I am trying to do filtering on a prop value and it changes based on dropdown selection.

Here is what I have so far:

template(v-for="field in tableFields")
   th(:id="field.name")

   select(@change="filterScope(scope)" v-model="selectedScope")
       option(v-for="scope in scopes" v-bind:value="scope" ) {{scope}}


template(v-for="(item) in tableData")
            row(
            :item="item"
            )

The first template is for the table header, the 2nd is the table row.

Assuming currently my table display data like this:

Name                  Age                  Gender
Andrew                 21                   Male
Dan                    21                   Male
Kate                   33                   Female

All these row's data are in the tableData variable, which is a prop and the parent defines the value. What I want to achieve is to enable drop down selection for Age and Gender.

For example, the dropdown for age will have option 21 and 33, if I chose 21, then the table will show as follows:

Name                  Age                  Gender
Andrew                 21                   Male
Dan                    21                   Male

My code so far is like this and I am not sure how to keep going:

 methods: {
     filterScope: function(scope) {
            var resultArray = []
            this.tableData.forEach(function(data){
                if (data.age === this.selectedScope) {
                    resultArray.push(data)
                }
            }, this);
            this.tableData = resultArray;
        }
 }

Error i am getting is:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "tableData"

This won't work for some reason and the data is not correctly filtered along with that warning from Vue. How do I properly filter the tableData?

1

1 Answers

0
votes

You can avoid mutating props using computed property:

template(v-for="(item) in filteredData")
            row(
            :item="item"
            )

and in javascript code

computed: {
  filteredData () {
    return this.tableData.filter((data) => data.age === this.selectedScope);
  }
}