
在 Uni-app 中,路由导航主要通过 uni.navigateTo、uni.redirectTo、uni.reLaunch 和 uni.switchTab 等 API 来实现。这些 API 的使用场景略有不同,适用于不同类型的页面跳转。 以下是一些常用的路由导航方法及其使用示例:
uni.navigateTo:保留当前页面,跳转到应用内的某个页面。使用 uni.navigateBack 可以返回到原页面。
javascript复制代码uni.navigateTo({ url: '/pages/detail/detail?id=123'});
uni.redirectTo:关闭当前页面,跳转到应用内的某个页面。
javascript复制代码uni.redirectTo({ url: '/pages/detail/detail?id=123'});
uni.reLaunch:关闭所有非 tabBar 页面,跳转到应用内的某个页面。
javascript复制代码uni.reLaunch({ url: '/pages/index/index'});
uni.switchTab:跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
javascript复制代码uni.switchTab({ url: '/pages/tab/home'}); 参数传递 在 URL 中传递参数时,可以通过 ? 后面的键值对传递,然后在目标页面中通过 onLoad 生命周期函数接收这些参数。 例如,传递参数: javascript复制代码uni.navigateTo({ url: '/pages/detail/detail?id=123&name=John'}); 在目标页面中接收参数: javascript复制代码Page({ onLoad: function (options) { console.log(options.id); // 输出 123 console.log(options.name); // 输出 John }}); 注意事项
tabBar 页面:在 Uni-app 中,tabBar 页面需要在 pages.json 中进行配置,且路径需要是固定的。使用 uni.switchTab 只能跳转到 tabBar 页面。 路径问题:确保 URL 路径正确,且目标页面已经在 pages.json 中注册。 返回机制:使用 uni.navigateTo 时,用户可以通过点击左上角的返回按钮或调用 uni.navigateBack 返回上一页面。
示例:完整页面跳转流程
假设我们有两个页面:pages/home/home 和 pages/detail/detail。
在 pages/home/home 页面中,我们有一个按钮用于跳转到 pages/detail/detail 页面:
html复制代码
