我有以下计算函数,因此根据搜索输入字段过滤我的房屋。这很有效。
computed: {
filtered: function() {
var self = this;
let searchTerm = (this.search || "").toLowerCase()
if(this.houses) {
return this.houses.filter(function(item) {
let city = (item.city || "").toLowerCase()
let street = (item.street || "").toLowerCase()
return city.indexOf(searchTerm) > -1 || street.indexOf(searchTerm) > -1;
})
}
}
}
但如何在城市和街道上实施订购呢? asc和desc。
这是表格:
<input type="search" v-model="search" placeholder="Search for City OR Street" />
<table>
<thead>
<tr>
<th @click="sortByStreet()">Street</th>
<th @click="sortByCity()">City</th>
</tr>
</thead>
<tbody>
<tr v-for="house in filtered">
<td>{{ house.street }}</td>
<td>{{ house.city }}</td>
</tr>
</tbody>
</table>
如何使用sortByStreet()
和sortByCity()
功能修复它?结合过滤器。
答案 0 :(得分:3)
您的click
应设置一个变量,称之为sortBy
,计算器用于确定如何对其结果进行排序。当变量发生变化时,计算机将重新计算。
new Vue({
el: '#app',
data: {
search: 'Z-town',
reverse: false,
houses: [{
street: 'First',
city: 'Z-town'
},
{
street: 'Second',
city: 'A-town'
},
{
street: 'First',
city: 'A-town'
},
{
street: 'Second',
city: 'Z-town'
}
],
sortBy: 'street'
},
computed: {
filtered: function() {
const result = this.houses
.filter(entry => [entry.street, entry.city].find(x => x === this.search))
.sort((a, b) =>
a[this.sortBy] < b[this.sortBy] ? -1 : a[this.sortBy] !== b[this.sortBy]
);
return this.reverse ? result.reverse() : result;
}
}
});
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<input type="search" v-model="search" placeholder="Search for City OR Street" />
<input type="checkbox" v-model="reverse"> Descending
<table>
<thead>
<tr>
<th @click="() => sortBy = 'street'">Street</th>
<th @click="() => sortBy = 'city'">City</th>
</tr>
</thead>
<tbody>
<tr v-for="house in filtered">
<td>{{ house.street }}</td>
<td>{{ house.city }}</td>
</tr>
</tbody>
</table>
</div>
&#13;