uni-app跳转页面的两种方式
在使用
uni-app
时,想在登录后跳转到index
页面,使用uni.navigateTo()
,结果报错errMsg: "navigateTo:fail can not navigateTo a tabbar page"
,通过将uni.navigateTo()
改为uni.switchTab()
,问题得到解决。在此对uni-app
页面跳转的两种方式进行总结。
1 通过navigator
标签跳转
<template>
<view>
<navigator url="/pages/about/about">
<button type="default">通过navigator组件跳转到about页面</button>
</navigator>
</view>
</template>
uni-app
的navigator
标签是用于页面跳转的组件。它可以通过点击触发页面的跳转,类似于HTML的a
标签。
navigator
标签的属性包括
url
:跳转的目标页面路径
open-type
:跳转方式,可选值包括navigateTo
、redirectTo
、switchTab
、reLaunch
、navigateBack
等
delta
:返回的页面数,当open-type
为navigateBack
时生效
hover-class
:点击时的样式类
hover-stop-propagation
:是否阻止事件冒泡
hover-start-time
:按下后多久出现点击态,单位毫秒
hover-stay-time
:手指松开后点击态保留时间,单位毫秒
2 通过方法实现跳转
<template>
<view>
<button type="default" @click="goto('/pages/about/about')">通过方法跳转到about页面</button>
</view>
</template>
<script>
export default {
methods: {
goto(url) {
uni.navigateTo({
url: url
})
}
}
}
</script>
定义点击事件,当button
被点击后通过uni.navigateTo()
方法跳转页面。
我的目标是在点击按钮后跳转到主页,却报了个错误errMsg: "navigateTo:fail can not navigateTo a tabbar page"
,经搜集资料发现,使用uni.switchTab()
替代uni.navigateTo()
,可以实现功能。
uni.switchTab()
和uni.navigateTo()
的区别
-
uni.switchTab()
用于tabBar
页面间的跳转,只能跳转到tabBar
页面,而uni.navigateTo()
可以跳转到任意页面。 -
uni.switchTab()
不会触发目标页面的onLoad
方法和onShow
方法,因为tabBar
页面已经在app启动时加载过了,而uni.navigateTo()
会触发目标页面的onLoad
方法和onShow
方法。 -
uni.switchTab()
不支持传递参数,因为tabBar
页面的参数已经在app启动时加载过了,而uni.navigateTo()
可以通过url传递参数。 -
uni.switchTab()
不能返回上一个页面,只能通过另外一个tabBar
页面或者在当前页面通过uni.reLaunch()
方法跳转回来,而uni.navigateTo()
可以通过uni.navigateBack()
方法返回上一个页面。