在 UniApp 中獲取當前頁面地址,可以通過以下步驟實現:
方法說明:
-
獲取當前頁面實例:使用?
getCurrentPages()
?獲取頁面棧數組,最后一個元素即為當前頁面實例。 -
提取頁面路徑和參數:從頁面實例的?
route
?屬性獲取路徑,options
?屬性獲取參數。 -
拼接完整地址:將路徑和參數組合成完整 URL。
function getCurrentUrl() {// 獲取頁面棧const pages = getCurrentPages();if (pages.length === 0) return;// 當前頁面實例const currentPage = pages[pages.length - 1];// 頁面路徑(補全前綴)const path = `/${currentPage.route}`;// 處理參數(編碼特殊字符)const queryParams = currentPage.options || {};const queryString = Object.keys(queryParams).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`).join('&');// 完整地址const fullUrl = queryString ? `${path}?${queryString}` : path;console.log('當前頁面地址:', fullUrl); // 輸出如:/pages/index/index?id=123
}
注意事項:
-
平臺差異:H5 端路徑可能包含協議和域名,但建議使用上述跨平臺方法。
-
生命周期限制:在?
App.onLaunch
?等過早時機調用可能導致頁面棧未生成。 -
參數編碼:使用?
encodeURIComponent
?處理特殊字符,確保 URL 合法性。
擴展場景:
-
H5 端獲取完整 URL:若需包含協議和域名(僅 H5 有效):
// 僅適用于 H5 環境
const fullH5Url = window.location.href;
通過上述方法,可跨平臺獲取當前頁面的路徑及參數,適用于需要動態處理頁面地址的場景。