小程序页面之间跳转的方式

先导


我们Activity和Fragment都有栈的概念在里面,微信小程序页面也有栈的概念在里面。微信小程序页面跳转有四种方式:


1
wx.navigateTo(OBJECT)
1
wx.redirectTo(OBJECT)
1
wx.switchTab(OBJECT)
1
wx.navigateBack(OBJECT)

分析

1.其中navigateTo是将原来的页面保存在页面栈中,在跳入到下一个页面的时候目标页面也进栈,只有在这个情况下点击手机的返回按钮才可以跳转到上一个页面;
2.redirectTo和switchTab都是先清除栈中原来的页面,然后目标页面进栈,使用这两种跳转方式,都不能通过系统的返回键回到上一个页面,而是直接退出小程序;
3.redirectTo使用的时候一定要配合tabBar或是页面里面可以再次跳转按钮,否则无法回到上一个页面;
4.switchTab跳转的页面必须是tabBar中声明的页面;
5.tabBar中定义的字段不能超过5个页面,小程序的页面栈层次也不能超过5层。
6.navigateBack只能返回到页面栈中的指定页面,一般和navigateTo配合使用。
7.wx.navigateTo 和 wx.redirectTo 不允许跳转到 tabbar 页面,只能用 wx.switchTab 跳转到 tabbar 页面

页面跳转的具体操作

(1) wx.navigateTo(OBJECT)

保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。
示例代码:

1
wx.navigateTo({ url: 'test?id=1'//实际路径要写全 })

(2) wx.redirectTo(OBJECT)

关闭当前页面,跳转到应用内的某个页面。
示例代码:

1
wx.redirectTo({ url: 'test?id=1' })

(3) wx.switchTab(OBJECT)

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
示例代码:

1
2
3
{ "tabBar": { "list": [{ "pagePath": "index", "text": "首页" },{ "pagePath": "other", "text": "其他" }] } }

wx.switchTab({ url: '/index' })

(4) wx.navigateBack(OBJECT)

关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages()) 获取当前的页面栈,决定需要返回几层。
注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈,而 redirectTo 方法则不会。
示例代码:

1
wx.navigateTo({ url: 'B?id=1' })

(5) 使用标签实现页面跳转

页面链接

示例代码:

1
"navigate?title=navigate" hover-class="navigator-hover">跳转到新页面 "redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">在当前页打开 "index" open-type="switchTab" hover-class="other-navigator-hover">切换 Tab

参数传递

通过路径传递参数

通过路径传递参数在wx.navigateTo(OBJECT)、wx.redirectTo(OBJECT)和中使用方法相同 示例代码:以wx.navigateTo为代表

1
2
3
wx.navigateTo({ url: 'test?id=1'//实际路径要写全 })

test.js Page({ onLoad: function(option){ console.log(option.id) } })

参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;
test?id=1 中id为参数键,1 为参数值
在目的页面中onLoad()方法中option对象即为参数对象,可以通过参数键来取出参数值​​​​

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!