首页 > 解决方案 > 我需要使用对象的属性对 Vue 中的对象数组进行排序,但 Vue 进入无限循环进行排序

问题描述

vue js对具有属性的对象数组进行排序,并尝试使用另一个属性对该排序后的数组进行排序,但Vue进入无限循环的排序

chatRoomArraySorted: function() {
    console.log("func name chatRoomArraySorted");

    function compare(a, b) {
        if (a.name < b.name)
            return -1;
        if (a.name > b.name)
            return 1;
        return 0;
    }

    return this.chatRoomsArray.sort(compare);
}

sortedArray: function() {
    this.log("sortedArray");

    function compare1(a, b) {
        return new Date(b.lastMsg.createdAt) - new Date(a.lastMsg.createdAt);
    }

    return this.chatRoomsArray.sort(compare1);
},

标签: javascriptsortingwebvuejs2

解决方案


每当它们依赖的任何属性的值发生变化时,计算属性都会更新,这意味着将再次调用定义函数。

由于您在两个计算属性中都调用sort()了该chatRoomsArray属性,因此您正在改变chatRoomsArray数组本身,从而触发两个计算属性的更新。每次运行每个计算属性的函数时都会发生这种情况,这会创建无限循环。


您需要做的是chatRoomsArray在每个计算属性中返回一个已排序的副本,而无需实际对数组本身进行排序。

您可以通过如下调用来制作数组的副本concat()

return this.chatRoomsArray.concat().sort(compare);

您还可以使用扩展语法来制作副本,如下所示:

return [...this.chatRoomsArray].sort(compare);

推荐阅读