Vue.js排序和过滤数据

时间:2018-08-10 12:58:12

标签: javascript sorting vue.js

我正在尝试对数据进行排序和过滤。我有一些API卡。 对于排序,我几乎没有问题(按价格对卡进行排序,按时间进行排序等) 默认排序是按价格排序,已启用。

过滤器是应该显示/隐藏我的卡片的输入(例如:最小价格和最大价格的范围)

我已经完成了过滤器,但是当我尝试按时间对项目进行排序时,过滤器的v-show逻辑从以前的排序(按价格排序)中保存了

卡来自Mounted()axios响应

Result.vue

排序按钮

<div class="sort-btn down" v-bind:class="{ activesort: activesort }" 
    v-on:click='changeSort'>By Price
</div>
<div class="sort-btn down" v-bind:class="{ activesort: !activesort }" 
    v-on:click='changeSort'>By Time
</div>

卡组件

<card :item="item" v-for="(item, index) in filteredAndSortedData"
:key="index"></card>

JS

computed: {
            filteredAndSortedData() {
                let result = this.cards;
                if(this.orderByTime){
                    return result.items.sort(function(a, b) {
                        return a.info.time - b.info.time;
                    });
                } else {
                    return result.items.sort(function(a, b) {
                        return a.price - b.price;
                    });
                }

            }
        }

data() {
    return {
        activesort: true,
        orderByTime: false,
        showFilters: false,
    }
},

methods: {
    changeSort: function () {
        this.activesort = !this.activesort;
        this.orderByTime = !this.orderByTime;
    },
}

Card.vue

<div class="card-wrapper" v-bind:class="{'has-label': hasLabel}" v-show="showCard">
    <div>{{item.price}}</div>
    <div>{{item.time}}</div>
</div>

data () {
    return {
        showCard: true,
    }
},

methods: {
    changeFilter() {
        if(some logic when clicking input){
            this.showCard = false;
        }
    }
}

因此,问题是:我有两个排序按钮,几个过滤器按钮。 当我尝试更改排序然后使用“过滤器”按钮时,它可以正常工作。 但是,当我尝试先过滤然后更改排序时,我得到了已排序的卡片,但是过滤器无法正常工作

我还设置了一个js fiddle来代表我想要的东西。

1 个答案:

答案 0 :(得分:1)

您为什么不添加:

foreach(double[] coordinate in data.coordinates) { coordinatesCenter.Add(new Vector2d(coordinate[0], coordinate[1])); coordinatesLeft.Add(new Vector2d(coordinate[0] + roadOffset, coordinate[1] + roadOffset)); coordinatesRight.Add(new Vector2d(coordinate[0] - roadOffset, coordinate[1] - roadOffset)); }

在排序之前?不需要您的观察者和待办事项中的result = result.filter(todo => todo.price >= this.price);属性。

https://jsfiddle.net/3wLtk6zn/4/

编辑:如果您想用观察者来做,也有可能: https://jsfiddle.net/3wLtk6zn/8/

代码不起作用的原因是,每次重新计算show属性时,您都将todos设置为包含所有项目的数组,并且观察者仅在更改价格时才过滤结果,因此更改排序方法会“取消过滤”数组。可以通过将result移到计算属性之外来固定到result

相关问题