小程序獲取當前頁面
在小程序中,所有頁面的路由都由框架統一管理。
框架以棧的形式維護了當前的所有頁面。
getCurrentPages() 函數用于獲取當前頁面棧的實例,以數組形式按棧的順序給出,第一個元素為首頁,最后一個元素為當前頁面。
注意:
1.不要嘗試修改頁面棧,會導致路由以及頁面狀態錯誤。
2.不要在 App.onLaunch 的時候調用 getCurrentPages(),此時 page 還沒有生成。
export function getCurrentPageUrl() { const pages = getCurrentPages() const currentPage = pages[pages.length - 1] const url = `/${currentPage.route}` return url } |
小程序獲取當前頁面路徑及參數
export function getCurrentPageUrlWithArgs() { const pages = getCurrentPages() const currentPage = pages[pages.length - 1] const url = currentPage.route const options = currentPage.options let urlWithArgs = `/${url}?` for (let key in options) { const value = options[key] urlWithArgs += `${key}=${value}&` } urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1) return urlWithArgs } |
由此可推,獲取上一個頁面 則是pages.lenght-2, 封到工具類里util.js非常實用