基本上我做错了什么?这是一个正在计算的链式过滤器。
错误是“product.topic.sort”不是函数。
我正在尝试使用“选择”来提供升序、降序、最高价格和最低价格的排序选项。
V-model 将值绑定(bind)到 js。
在过滤器下,我尝试添加一个过滤器,根据“值”进行排序
如果值=未定义,则不执行任何操作。
如果值 = Az,则升序
如果值 = Za,则降序
如果值(value) = Ph,则价格高
如果值(value) = Pl,则价格较低
编辑
在 filteredSearch() {
下,我还有其他过滤器,例如
.filter(product => this.filters.some(filter => product.topic.match(filter))) ||
this.products
.filter(p => p.topic.toLowerCase().match(this.search.toLowerCase()))
.filter(p => p.price <= this.priceFilter)
我想确保所有其他过滤器都可以与排序过滤器一起使用。
HTML
<div id="app">
<h4>Sort</h4>
<select v-model="value">
<option value="Az">Ascending</option>
<option value="Za">Descending</option>
<option value="Ph">Price High</option>
<option value="Pl">Price Low</option>
</select>
<div class="block" v-for="product in filteredSearch">
<h3>{{product.topic}}</h3>
<p>{{product.price}}</p>
</div>
</div>
JS
var app = new Vue({
el: '#app',
data: {
products: [{
"topic": "english",
"price": "20"
},
{
"topic": "french",
"price": "60"
},
{
"topic": "science",
"price": "80"
}
],
value: "",
})
computed: {
filteredSearch() {
return this.products
.filter((product) => {
if (!this.value)
return true;
if (this.value == "Az") {
return product.topic.sort(function(a, b) {
a.topic - b.topic
});
}
})
}
}
});
最佳答案
这是一个example如何做到这一点。因此,我们有一个辅助方法 getSorter
,它查看 v-model
指令绑定(bind)到 this.value
的当前选定值,并返回传递给 sort 的适当函数基于此。如果没有选择任何内容,它将返回null
。
在计算属性 filteredSearch
中,您可以根据需要应用现有过滤器,然后对结果进行排序。
methods: {
// determine the sorting function to use
getSorter() {
switch (this.value) {
case 'Za':
return (a,b) => b.topic > a.topic ? 1 : a.topic == b.topic ? 0 : -1;
case 'Az':
return (a,b) => b.topic > a.topic ? -1 : a.topic == b.topic ? 0 : 1;
case 'Ph':
return (a,b) => b.price - a.price;
case 'Pl':
return (a,b) => a.price - b.price;
default:
return null;
}
}
},
computed: {
filteredSearch: function() {
// apply existing filter logic
var filteredProducts = this.products
.filter((el) => true); // replace with your existing filter conditions here
// apply sort function
var sortFunction = this.getSorter();
return sortFunction ? filteredProducts.sort(sortFunction) : filteredProducts;
}
}
关于javascript - 在 Javascript 中使用 .filter 对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977316/