微信小程序页面跳转方法总结
微信小程序页面跳转目前有以下方法(不全面的欢迎补充):
1. 利用小程序提供的 API 跳转:
// 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 // 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈,但是 redirectTo wx.navigateTo({ url: 'page/home/home?user_id=111' }) // 关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。 wx.navigateTo({ url: 'page/home/home?user_id=111' // 页面 A }) wx.navigateTo({ url: 'page/detail/detail?product_id=222' // 页面 B }) // 跳转到页面 A wx.navigateBack({ delta: 2 }) // 关闭当前页面,跳转到应用内的某个页面。 wx.redirectTo({ url: 'page/home/home?user_id=111' }) // 跳转到tabBar页面(在app.json中注册过的tabBar页面),同时关闭其他非tabBar页面。 wx.switchTab({ url: 'page/index/index' }) // 关闭所有页面,打开到应用内的某个页面。 wx.reLanch({ url: 'page/home/home?user_id=111' })
2. wxml 页面组件跳转(可以通过设置open-type属性指明页面跳转方式):
// navigator 组件默认的 open-type 为 navigate <navigator url="/page/navigate/navigate?title=navigate" hover-class="navigator-hover">跳转到新页面</navigator> // redirect 对应 API 中的 wx.redirect 方法 <navigator url="../../redirect/redirect/redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">在当前页打开</navigator> // switchTab 对应 API 中的 wx.switchTab 方法 <navigator url="/page/index/index" open-type="switchTab" hover-class="other-navigator-hover">切换 Tab</navigator> // reLanch 对应 API 中的 wx.reLanch 方法 <navigator url="../../redirect/redirect/redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">关闭所有页面,打开到应用内的某个页面</navigator> // navigateBack 对应 API 中的 wx.navigateBack 方法 <navigator url="/page/index/index" open-type="navigateBack" hover-class="other-navigator-hover">关闭当前页面,返回上一级页面或多级页面</navigator>
<view class="itemWeight" catchtap="jumpToOverMissionList"> // 在js代码中写:其中,url是跳转的相对路径,?问号后面加的是参数,以key-value的方式,这里传了个value为2的参数过去 jumpToOverMissionList:function(){ wx.navigateTo({ url:"mission/missionList/missionList?type=2" }); },
3、跳转页面技巧(经验交流)
微信小程序某个页面直接返回首页(即微信小程序回退到首页)
打开小程序后,到三级页面后点击左上角的返回按钮,能够直接返回到首页
正常 A -> B -> C 都是通过 wx.navigateTo 跳转的,所以 wx.navigateBack 只能返回上一界面,如果要返回到A 界面就会出现 C -> B -> A 的效果。
如果想实现 A -> B -> C 当 C 点击返回时, 实现直接 C -> A 这种效果, 就只能A -> B 通过 wx.navigateTo 跳转,B -> C 通过 wx.redirectTo 跳转,跳转触发后 B 页面就会被销毁, C 页面再返回 wx.navigateBack 就会直接到 A 了。
例如:
第一个页面采用navigateTo,
wx.navigateTo({ url: '/pages/logs/logs', })
在第二个页面中使用redirectTo。
wx.redirectTo({ url: '/pages/test/test', })
这里是重点:在第三个页面点击回退时,会直接回到第一个页面。
wx.redirectTo()跳转到新页面之后,会自动销毁上一个页面,在新页面点击返回按钮时,会直接回到上上一个页面
这是相当于在这个回退过程中直接销毁第二个页面
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通