如何通过下拉选择操作道具值

How to manipulate prop value with drop down selection

我正在尝试对道具值进行过滤,它会根据下拉选择进行更改。

这是我目前的情况:

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"
            )

第一个模板用于 table header,第二个模板用于 table 行。

假设目前我的 table 显示这样的数据:

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

所有这些行的数据都在tableData 变量中,这是一个prop 并且parent 定义了值。我想要实现的是启用年龄和性别的下拉选择。

比如年龄下拉会有21和33选项,如果我选择21,那么table会显示如下:

Name                  Age                  Gender
Andrew                 21                   Male
Dan                    21                   Male

到目前为止我的代码是这样的,我不确定如何继续:

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

我得到的错误是:

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"

由于某些原因,这将不起作用,并且数据未正确过滤以及来自 Vue 的警告。 如何正确过滤 tableData?

您可以使用 computed 属性:

避免改变 props
template(v-for="(item) in filteredData")
            row(
            :item="item"
            )

并在 javascript 代码中

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