微信小程序中页面跳转主要有两种方式:声明式导航(通过组件实现)和编程式导航(通过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); // 输出 1 console.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); // 1 console.log(options.name); // test } })
三、页面栈与跳转限制
小程序的页面栈是一个数组,最多可容纳10个页面。使用wx.navigateTo
或默认声明式导航时,新页面会加入栈中;使用wx.redirectTo
时,当前页面会被移除栈,新页面加入;使用wx.switchTab
时,所有非tabBar页面会被移除栈。
当页面栈已满(10层),继续使用wx.navigateTo
会失败,需改用wx.redirectTo
。
四、两种方式的选择建议
若只需单纯跳转,无需前置逻辑,优先使用声明式导航(代码更简洁)。
若需要先执行逻辑(如验证、数据处理)再跳转,使用编程式导航。
跳转tabBar页面必须使用switchTab
(无论声明式还是编程式)。
需要返回多级页面时,编程式导航的wx.navigateBack
更灵活(可动态计算delta)。