基本上我做错了什么?这是计算下的链式过滤器。
错误是'product.topic.sort‘不是一个函数。
我试图使用“选择”来选择上升、下降、价格高和价格低的排序选项。
V模型将值绑定到js。
在“筛选器”下,我试图添加一个基于“值”进行排序的筛选器
如果值=未定义,则什么也不做。
如果值= Az,则上升
如果值= Za,降序
如果值= Ph,价格高
如果值= 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)我希望确保所有其他过滤器与排序过滤器一起工作。
<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
});
}
})
}
}
});发布于 2019-11-21 15:51:25
这是一个关于如何做到这一点的示例。因此,我们有一个帮助方法getSorter,它查看v-model指令绑定到this.value的当前选定的值,并返回一个适当的函数,在此基础上传递给排序。如果没有选择,它将返回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;
}
}发布于 2019-11-21 15:22:41
我认为您不应该在计算的属性函数中使用filter,最好这样做
filteredSearch() {
return !this.value ?
true
: this.value == "Az" ?
this.products.sort((a, b) => a.topic > b.topic ? 1 : -1)
: this.value == "Za" ?
this.products.sort((a, b) => a.topic < b.topic ? 1 : -1)
: this.value == "Pl" ?
this.products.sort((a, b) => a.price - b.price)
: this.value == "Ph" ?
this.products.sort((a, b) => b.price - a.price)
: null;
}https://stackoverflow.com/questions/58977316
复制相似问题