微信小程序中頁面跳轉主要有兩種方式:聲明式導航(通過組件實現)和編程式導航(通過API實現)。兩種方式適用于不同場景,以下詳細說明。
一、聲明式導航(navigator組件)
通過小程序內置的<navigator>
組件實現跳轉,無需編寫JavaScript代碼,直接在WXML中配置屬性即可。核心屬性為url
(目標頁面路徑)和open-type
(跳轉方式)。
1. 基本用法(默認跳轉:保留當前頁面)
默認情況下,open-type
為navigateTo
,跳轉后當前頁面會保留在頁面棧中,目標頁面可通過返回按鈕回到當前頁面。
<!-- 從當前頁面跳轉到 pages/detail/detail 頁面 --> <navigator url="/pages/detail/detail">跳轉到詳情頁</navigator>
注意:url
必須以/
開頭,表示項目根目錄下的路徑。
2. 重定向跳轉(關閉當前頁面)
設置open-type="redirect"
,跳轉時會關閉當前頁面,當前頁面不會保留在頁面棧中,目標頁面無法通過返回按鈕回到當前頁面。
<navigator url="/pages/detail/detail" open-type="redirect">重定向到詳情頁(關閉當前頁) </navigator>
3. 跳轉到tabBar頁面
若目標頁面是app.json
中配置的tabBar頁面(底部導航頁),需設置open-type="switchTab"
,跳轉時會關閉所有非tabBar頁面。
<!-- 假設 pages/index/index 是tabBar頁面 --> <navigator url="/pages/index/index" open-type="switchTab">跳轉到首頁(tabBar頁面) </navigator>
4. 返回上一頁(或多級頁面)
設置open-type="navigateBack"
,配合delta
屬性指定返回的層數(默認1層)。
<!-- 返回上一頁 --> <navigator open-type="navigateBack">返回</navigator><!-- 返回上兩層 --> <navigator open-type="navigateBack" delta="2">返回上兩層</navigator>
5. 傳遞參數
通過URL查詢字符串(?key=value&key2=value2
)傳遞參數,目標頁面在onLoad
生命周期中通過options
參數獲取。
<!-- 當前頁面傳遞參數 id=1 和 name=test --> <navigator url="/pages/detail/detail?id=1&name=test">帶參數跳轉到詳情頁 </navigator><!-- 目標頁面(detail.js)獲取參數 --> Page({onLoad(options) {console.log(options.id); // 輸出 1console.log(options.name); // 輸出 test} })
二、編程式導航(API調用)
通過調用微信小程序提供的導航API實現跳轉,需在JavaScript中編寫代碼,適用于需要先執行邏輯(如驗證登錄狀態)再跳轉的場景。
1. wx.navigateTo(保留當前頁面)
與聲明式導航的open-type="navigateTo"
功能一致,跳轉后保留當前頁面。
// 在當前頁面的.js文件中 Page({goToDetail() {wx.navigateTo({url: '/pages/detail/detail' // 目標頁面路徑});} })
在WXML中綁定事件觸發:<button bind:tap="goToDetail">跳轉到詳情頁</button>
2. wx.redirectTo(關閉當前頁面)
與聲明式導航的open-type="redirect"
功能一致,跳轉時關閉當前頁面。
Page({goToDetail() {wx.redirectTo({url: '/pages/detail/detail'});} })
3. wx.switchTab(跳轉到tabBar頁面)
與聲明式導航的open-type="switchTab"
功能一致,用于跳轉tabBar頁面。
Page({goToHome() {wx.switchTab({url: '/pages/index/index' // 目標tabBar頁面路徑});} })
4. wx.navigateBack(返回上一頁)
與聲明式導航的open-type="navigateBack"
功能一致,通過delta
指定返回層數。
Page({goBack() {wx.navigateBack({delta: 1 // 返回上一頁(默認1)});} })
5. 傳遞參數(與聲明式一致)
在url
中通過查詢字符串傳遞參數,目標頁面在onLoad
中獲取。
Page({goToDetail() {wx.navigateTo({url: '/pages/detail/detail?id=1&name=test'});} })// 目標頁面(detail.js) Page({onLoad(options) {console.log(options.id); // 1console.log(options.name); // test} })
三、頁面棧與跳轉限制
小程序的頁面棧是一個數組,最多可容納10個頁面。使用wx.navigateTo
或默認聲明式導航時,新頁面會加入棧中;使用wx.redirectTo
時,當前頁面會被移除棧,新頁面加入;使用wx.switchTab
時,所有非tabBar頁面會被移除棧。
當頁面棧已滿(10層),繼續使用wx.navigateTo
會失敗,需改用wx.redirectTo
。
四、兩種方式的選擇建議
若只需單純跳轉,無需前置邏輯,優先使用聲明式導航(代碼更簡潔)。
若需要先執行邏輯(如驗證、數據處理)再跳轉,使用編程式導航。
跳轉tabBar頁面必須使用switchTab
(無論聲明式還是編程式)。
需要返回多級頁面時,編程式導航的wx.navigateBack
更靈活(可動態計算delta)。