【问题标题】:Vuejs sort and filter dataVuejs 对数据进行排序和过滤
【发布时间】:2018-08-10 12:58:12
【问题描述】:

我正在尝试对我的数据进行排序和过滤。我有一些来自 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 来代表我想要的。

【问题讨论】:

    标签: javascript sorting vue.js


    【解决方案1】:

    你为什么不直接添加:

    result = result.filter(todo =&gt; todo.price &gt;= this.price);

    排序前?您的观察者和待办事项中的show 属性也不是必需的。

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

    编辑:如果你想用观察者的方式来做,也可以: https://jsfiddle.net/3wLtk6zn/8/

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

    【讨论】:

    • 这可以通过将计算属性之外的结果移动到数据来解决。我无法将其移动到数据中,因为结果是我安装的救生钩中的 API 响应,当页面渲染结果为空时,我得到了错误
    猜你喜欢
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多