navigator 是小程序頁面跳轉的核心組件,通過 URL Query String 傳遞參數:
<!-- 單參數 -->
<navigator url="/pages/detail/detail?id=123">跳轉</navigator>
<!-- 多參數 -->
<navigator url="/pages/detail/detail?id=123&name=abc&type=1">跳轉</navigator>
在目標頁面的 onLoad(options) 生命周期中直接獲取:
Page({
onLoad(options) {
console.log(options.id); // "123"
console.log(options.name); // "abc"
console.log(options.type); // "1"
// options 是包含所有 query 參數的對象
}
})
注意:參數值均為字符串,需自行 parseInt 等轉換。
wx.navigateTowx.navigateTo({
url: '/pages/detail/detail?id=' + encodeURIComponent(id) + '&name=' + encodeURIComponent(name)
})
涉及特殊字符(&、=、空格、中文)時,必須使用 encodeURIComponent 編碼,目標頁面自動解碼。
// 獲取 URL 中指定參數值
function GetQueryString(name) {
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
const r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}
// 使用示例
// URL: https://example.com/page?source=google&keyword=微信小程序
GetQueryString('source'); // "google"
GetQueryString('keyword'); // "微信小程序" (自動解碼)
GetQueryString('none'); // null
| 特性 | 微信小程序 | Web (H5) |
|---|---|---|
| 跳轉組件 | <navigator> / wx.navigateTo | <a href> / location.href |
| 參數獲取 | onLoad(options) | location.search + 正則 / URLSearchParams |
| 編碼要求 | 手動 encodeURIComponent | 瀏覽器自動編碼/解碼 |
| 參數長度限制 | URL 總長 ≤ 2048 字符 | 瀏覽器/服務器限制不一(通常 2KB-8KB) |
wx.setStorage 或登錄態換取。wx.navigateTo 搭建參數對象,或通過全局 getApp().globalData 傳遞。new URLSearchParams(location.search).get('name') 替代正則。