13、路由导航跳转

uniapp中路由跳转有如下两种方式:

1、声明式路由跳转

声明式路由跳转通过navigator实现

页面跳转。该组件类似HTML中的<a>组件,但只能跳转本地页面。目标页面必须在pages.json中注册。参考官网:组件->内置组件->uni-app组件->路由与页面跳转

要跳转的页面必须注册路由:

image

要注册:
image

普通跳转

<navigator url="/pages/detail/detail">跳转至详情页</navigator>

redirect方式

<navigator url="/pages/detail/detail" open-type="redirect">跳转至详情页(redirect方式)</navigator>

这种方式会关闭当前页,触发当前组件的卸载生命周期函数。比如:我们定义该组件的卸载函数。

image

点击跳转后就会触发:
image

普通的跳转可以返回的(不管是点上面箭头还是浏览器的回退按钮,都可返回):
image


跳转至tabBar里的页面

<navigator url="/pages/message/message" open-type='switchTab' >跳转至tabBar里的页面</navigator>


2、编程式路由跳转

参考官网:API->路由与页面跳转

普通跳转uni.navigateTo(OBJECT)

保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。

如:uni.navigateTo({url:'/pages/detail/detail'});

OBJECT参数说明

image

redirect方式uni.redirectTo(OBJECT)

关闭当前页面,跳转到应用内的某个页面。会触发当前组件卸载函数。

如:uni.redirectTo({url:'/pages/detail/detail'})

跳转至tabBar里的页面uni.switchTab(OBJECT)

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
如果调用了 uni.preloadPage(OBJECT) (opens new window)不会关闭,仅触发生命周期 onHide

如:uni.switchTab({url:'/pages/message/message'})

上面演示代码

<template>
	<view>
		<view><h1>声明式导航的学习</h1></view>
		
		<navigator url="/pages/detail/detail">跳转至详情页</navigator>
		
		<navigator url="/pages/detail/detail" open-type="redirect">跳转至详情页(redirect方式)</navigator>
		
		<navigator url="/pages/message/message" open-type='switchTab' >跳转至tabBar里的页面</navigator>
		
		<button @click="goDetail">跳转至详情页</button>
		<button @click="goDetailByRedirect">跳转至详情页(redirect方式)</button>
		<button @click="goMessage">跳转至tabBar里的页面</button>
		
	</view>
</template>

<script>
	export default{
		
		onUnload() {
			console.log('触发了组件卸载事件');
		},
		
		methods:{
			goDetail(){
				uni.navigateTo({url:'/pages/detail/detail'});
			},
			goDetailByRedirect(){
				uni.redirectTo({url:'/pages/detail/detail'})
			},
			goMessage(){
				uni.switchTab({url:'/pages/message/message'})
			}
		}
	}
</script>
posted @ 2022-06-23 22:39  青仙  阅读(253)  评论(0编辑  收藏  举报