encodeURIComponent和encodeURIComponent
是的,在微信小程序中跳转页面时,如果你要通过 URL 参数传递 特殊字符(比如 /
, ?
, =
, &
等),必须使用 encodeURIComponent
进行编码,否则可能会导致参数解析出错或页面无法跳转。
🧠 为什么要用 encodeURIComponent
?
微信小程序跳转页面通常是这样写的:
上面这个 URL 是有问题的:
?redirect=/pages/user/profile?id=123&type=edit
—— 这个字符串中有 两个问号 和多个等号、& 符号,微信小程序的路由解析器会把后面的参数解析错乱。
✅ 正确做法是:
🔁 在跳转时使用 encodeURIComponent
const redirect = encodeURIComponent('/pages/user/profile?id=123&type=edit');
uni.navigateTo({
url: `/pages/login/index?redirect=${redirect}`
});
🔓 在接收时使用 decodeURIComponent
onLoad(options) {
const redirect = options.redirect ? decodeURIComponent(options.redirect) : null;
console.log('跳转回来要去的页面是:', redirect);
}
💡 简单对比如下:
场景 | 示例 | 是否需要编码 |
---|---|---|
参数中不含特殊字符 | ?redirect=/pages/home/index |
❌ 可以不编码 |
参数中包含 ? 、& 、= 等 |
?redirect=/pages/user/profile?id=123&type=edit |
✅ 必须编码 |
🧪 小测试
const url = '/pages/user/profile?id=123&type=edit';
console.log(encodeURIComponent(url));
// 输出: %2Fpages%2Fuser%2Fprofile%3Fid%3D123%26type%3Dedit
✅ 总结
- 跳转参数中带特殊字符时,必须用
encodeURIComponent
。 - 防止页面路由解析错误或参数丢失。
- 跳转目标页面要使用
decodeURIComponent
还原原始值。
需要我帮你写个跳转带参数、自动返回原页面的完整模板吗?