【问题标题】:Vuejs2 - List rendering filtered with computed propertiesVuejs2 - 使用计算属性过滤的列表渲染
【发布时间】:2019-04-24 01:13:38
【问题描述】:

我在列表渲染和使用计算属性过滤数据方面遇到了一些问题

我想使用 filterKey 来过滤 row.age,而不是硬编码 row.age 值。

如何归档?我就是不明白。

这是我的例子:

模板:

<button type="button" class="btn btn-t1-secondary" v-on: click="filterKey = '15'">11</button>
<button type="button" class="btn btn-t1-secondary" v-on: click="filterKey = '30'">8</button>

<table>
    <thead>
        <tr>
            <th>Category</th>
            <th>Age</th>
            <th>Food</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="row in filteredCategory">
            <td>{{ row.category }}</td>
            <td>{{ row.age }}</td>
            <td>{{ row.food }}</td>
        </tr>
    </tbody>
</table>

JavaScript:

<script>
var app = new Vue({
  el: '#app',
  data: {
    filterKey: '',
    filterCategory: '',
    dataToFilter: [
      {
        category: 'dog',
        age: '11',
        food: 'bone'
      },
      {
        category: 'cat',
        age: '8',
        food: 'fish'
      }
      //etc.
    ]
  },
  computed: {
    filteredCategory() {
      return this.dataToFilter.filter(function (row) {
        return row.category === 'dog'
      })
        .filter(function (row) {
          console.log(this.filterKey)
          return row.age === '15'
        })
    },
  }
})
</script>

解决方案

正如@Sadraque_Santos 建议的那样,我使用了箭头函数。

代码

filteredCategory() {
return this.dataToFilter.filter( r => r.category === 'dog' && r.age === this.filterKey);
}

另外,我必须支持 IE11,所以我只使用 Babel 为我编译代码。

【问题讨论】:

    标签: vue.js computed-properties


    【解决方案1】:

    要在filtermap 或其他有用的方法中访问this,您必须了解arrow functions,它们允许您创建一个没有this 绑定到该对象的函数,因此使用:

    filteredCategory () {
      return this.dataToFilter.filter(function (row) {
        return row.category === 'dog'
      })
        .filter(function (row) {
          console.log(this.filterKey)
          return row.age === '15'
        })
    }
    

    你的代码应该是这样的:

        filteredCategory () {
          return this.dataToFilter
            .filter((row) => row.category === this.filterCategory)
            .filter((row) => row.age === this.filterKey)
        }
    

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2020-03-09
      • 2019-05-06
      相关资源
      最近更新 更多