修复 isObjectEqual 函数
首先,查看左侧文件的目录结构如下:
├── vue-router-2.7.0
├── vue.min.js
└── index.html
点击 WebIDE 右下角的 Go Live 按钮来运行项目。
接下来,在虚拟机顶部打开 “Web 8080” 并手动刷新,点击 “test” 并在浏览器控制台中打开 Console
选项,你会看到两条错误消息,分别是 TypeError: Cannot convert undefined or null to object
和 Uncaught TypeError: Cannot convert undefined or null to object
。
在这一步中,你将学习如何修复 vue-router-2.7.0/src/util/route.js
文件中的 isObjectEqual
函数,以正确处理 null
值。
打开 vue-router-2.7.0/src/util/route.js
文件。
找到 isObjectEqual
函数:
function isObjectEqual(a = {}, b = {}): boolean {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length!== bKeys.length) {
return false;
}
return aKeys.every((key) => {
const aVal = a[key];
const bVal = b[key];
// 检查嵌套相等性
if (typeof aVal === "object" && typeof bVal === "object") {
return isObjectEqual(aVal, bVal);
}
return String(aVal) === String(bVal);
});
}
更新函数以正确处理 null
值:
function isObjectEqual(a = {}, b = {}): boolean {
if (!a ||!b) return a === b;
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length!== bKeys.length) {
return false;
}
return aKeys.every((key) => {
const aVal = a[key];
const bVal = b[key];
// 检查嵌套相等性
if (typeof aVal === "object" && typeof bVal === "object") {
return isObjectEqual(aVal, bVal);
}
return String(aVal) === String(bVal);
});
}
更改内容如下:
添加了一个条件来检查 a
或 b
是否为 null
或 undefined
。如果其中任何一个是 null
或 undefined
,函数将返回 a === b
。
这确保了函数能够正确处理 query
参数中的 null
值。