javascript - 我需要使用对象的属性对 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);
},
解决方案
每当它们依赖的任何属性的值发生变化时,计算属性都会更新,这意味着将再次调用定义函数。
由于您在两个计算属性中都调用sort()
了该chatRoomsArray
属性,因此您正在改变chatRoomsArray
数组本身,从而触发两个计算属性的更新。每次运行每个计算属性的函数时都会发生这种情况,这会创建无限循环。
您需要做的是chatRoomsArray
在每个计算属性中返回一个已排序的副本,而无需实际对数组本身进行排序。
您可以通过如下调用来制作数组的副本concat()
:
return this.chatRoomsArray.concat().sort(compare);
您还可以使用扩展语法来制作副本,如下所示:
return [...this.chatRoomsArray].sort(compare);
推荐阅读
- aframe - webflow中的A-Frame占据了整个屏幕
- pre-commit - 使用预提交排除一些运行黑色的文件
- java - 从多个列表中生成所有可能的组合
- node.js - Firebase 功能部署不工作,被 [ 服务器错误拒绝。客户端网络套接字断开]
- java - 图像未在 Android 中显示
- r - 如何将值分组为数据集中的较小值集?
- javascript - Flask wtforms Integerfield() 返回 NaN
- mongodb - Mongod 身份验证使 GCP VM 无法访问
- sql - 如何将同一表中的行与每个表的默认行进行比较?
- excel - VBA - 将 A 列到 I 列复制到本书末尾的新工作表中