【发布时间】: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