【uniapp小程序】路由跳转navigator传参封装

1,828 阅读7分钟

🍍前言

在实际应用开发中我们经常要使用到路由跳转,在uniapp官网中,提供了navigator内置组件,供我们使用。官网地址:navigator页面跳转

🍋正文

1、看官网

1.1 navigator API 介绍

页面跳转。

该组件类似HTML中的<a>组件,但只能跳转本地页面。目标页面必须在pages.json中注册。

该组件的功能有API方式,另见:uniapp.dcloud.io/api/router?…

属性说明

属性名类型默认值说明平台差异说明
urlString应用内的跳转链接,值为相对路径或绝对路径,如:"../first/first","/pages/first/first",注意不能加 .vue 后缀
open-typeStringnavigate跳转方式
deltaNumber当 open-type 为 'navigateBack' 时有效,表示回退的层数
animation-typeStringpop-in/out当 open-type 为 navigate、navigateBack 时有效,窗口的显示/关闭动画效果,详见:窗口动画App
animation-durationNumber300当 open-type 为 navigate、navigateBack 时有效,窗口显示/关闭动画的持续时间。App
hover-classStringnavigator-hover指定点击时的样式类,当hover-class="none"时,没有点击态效果
hover-stop-propagationBooleanfalse指定是否阻止本节点的祖先节点出现点击态微信小程序
hover-start-timeNumber50按住后多久出现点击态,单位毫秒
hover-stay-timeNumber600手指松开后点击态保留时间,单位毫秒
targetStringself在哪个小程序目标上发生跳转,默认当前小程序,值域self/miniProgram微信2.0.7+、百度2.5.2+、QQ

open-type 有效值

说明平台差异说明
navigate对应 uni.navigateTo 的功能
redirect对应 uni.redirectTo 的功能
switchTab对应 uni.switchTab 的功能
reLaunch对应 uni.reLaunch 的功能字节跳动小程序与飞书小程序不支持
navigateBack对应 uni.navigateBack 的功能
exit退出小程序,target="miniProgram"时生效微信2.1.0+、百度2.5.2+、QQ1.4.7+

注意

  • 跳转tabbar页面,必须设置open-type="switchTab"
  • navigator-hover 默认为 {background-color: rgba(0, 0, 0, 0.1); opacity: 0.7;}, <navigator> 的子节点背景色应为透明色。
  • navigator-open-type属性 如果使用对应的值,则对应值的功能会高于对应跳转路径。
  • app-nvue 平台只有纯nvue项目(render为native)才支持 <navigator>。非render为native的情况下,nvue暂不支持navigator组件,请使用API跳转。
  • app下退出应用,Android平台可以使用plus.runtime.quit。iOS没有退出应用的概念。
  • uLink组件是navigator组件的增强版,样式上自带下划线,功能上支持打开在线网页、其他App的schema、mailto发邮件、tel打电话。

1.2、路由跳转参数传递

url有长度限制,太长的字符串会传递失败,可使用窗体通信、全局变量,或encodeURIComponent等多种方式解决,如下为encodeURIComponent示例。

<navigator :url="'/pages/navigate/navigate?item='+ encodeURIComponent(JSON.stringify(item))"></navigator>
// navigate.vue页面接受参数
onLoad: function (option) {
	const item = JSON.parse(decodeURIComponent(option.item));
}

1.3、五种常见的跳转方式

以下只做简单的介绍,详细说明和案例可移步官方文档

1.3.1 uni.navigateTo(OBJECT)

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

注: 因为我们今天封装路由跳转主要使用的是navigateTo,所以我将官方的文档复制了过来可以看下详细的参数介绍。

OBJECT参数说明

参数类型必填默认值说明平台差异说明
urlString需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数。参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;如 'path?key=value&key2=value2',path为下一个页面的路径,下一个页面的onLoad函数可得到传递的参数
animationTypeStringpop-in窗口显示的动画效果,详见:窗口动画App
animationDurationNumber300窗口动画持续时间,单位为 msApp
eventsObject页面间通信接口,用于监听被打开页面发送到当前页面的数据。2.8.9+ 开始支持。
successFunction接口调用成功的回调函数
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

object.success 回调函数

参数

Object res

属性类型说明
eventChannelEventChannel和被打开页面进行通信

示例

//在起始页面跳转到test.vue页面并传递参数
uni.navigateTo({
	url: 'test?id=1&name=uniapp'
});
// 在test.vue页面接受参数
export default {
	onLoad: function (option) { //option为object类型,会序列化上个页面传递的参数
		console.log(option.id); //打印出上个页面传递的参数。
		console.log(option.name); //打印出上个页面传递的参数。
	}
}
// 在起始页面跳转到test.vue页面,并监听test.vue发送过来的事件数据
uni.navigateTo({
  url: 'pages/test?id=1',
  events: {
    // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
    ...
  },
  success: function(res) {
    // 通过eventChannel向被打开页面传送数据
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'data from starter page' })
  }
})

// 在test.vue页面,向起始页通过事件传递数据
onLoad: function(option) {
  const eventChannel = this.getOpenerEventChannel();
  eventChannel.emit('acceptDataFromOpenedPage', {data: 'data from test page'});
  eventChannel.emit('someEvent', {data: 'data from test page for someEvent'});
  // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
  eventChannel.on('acceptDataFromOpenerPage', function(data) {
    console.log(data)
  })
}

url有长度限制,太长的字符串会传递失败,可改用窗体通信全局变量,另外参数中出现空格等特殊字符时需要对参数进行编码,如下为使用encodeURIComponent对参数进行编码的示例。

<navigator :url="'/pages/test/test?item='+ encodeURIComponent(JSON.stringify(item))"></navigator>
// 在test.vue页面接受参数
onLoad: function (option) {
	const item = JSON.parse(decodeURIComponent(option.item));
}

注意:

  • 页面跳转路径有层级限制,不能无限制跳转新页面
  • 跳转到 tabBar 页面只能使用 switchTab 跳转
  • 路由API的目标页面必须是在pages.json里注册的vue页面。如果想打开web url,在App平台可以使用 plus.runtime.openURL或web-view组件;H5平台使用 window.open;小程序平台使用web-view组件(url需在小程序的联网白名单中)。在hello uni-app中有个组件ulink.vue已对多端进行封装,可参考。

1.3.2 uni.redirectTo(OBJECT)

关闭当前页面,跳转到应用内的某个页面。

1.3.3 uni.reLaunch(OBJECT)

关闭所有页面,打开到应用内的某个页面。

1.3.4 uni.switchTab(OBJECT)

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。

1.3.5 uni.navigateBack(OBJECT)

关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。默认值为1。

2、路由跳转传参简易封装

2.1、首先列举一下需要考虑的参数

  • URL :目标地址
  • params:有没有携带参数跳转
  • openType :跳转方式(文档里名字为open-type)
  • animation-type:当 open-typenavigatenavigateBack 时有效,窗口的显示/关闭动画效果。
  • animation-duration:窗口显示/关闭动画的持续时间。

2.2、封装代码

本示例代码封装在mina.js 文件

// openType 默认值为 navigate;animationType 默认值为pop-in;animationDuration 默认值为300毫秒
Vue.prototype.goByPath = function(path, params, openType = 'navigate', animationType = 'pop-in', animationDuration =
	300) {
	// 有参数执行这里的逻辑
	if(params !==undefined && params !== null){
		if (openType == 'navigate') {
		// 如果跳转方式为navigate,则使用navigateTo方式跳转,保留当前页面,跳转到应用内的某个页面
			uni.navigateTo({
				url: path + "?params=" + encodeURIComponent(JSON.stringify(params)),
				animationType: animationType,
				animationDuration: animationDuration
			})
		} else {
		// 如果跳转方式不为navigate,则使用redirectTo方式跳转,关闭当前页面,跳转到应用内的某个页面
			uni.redirectTo({
				url: path + "?params=" + encodeURIComponent(JSON.stringify(params)),
				animationType: animationType,
				animationDuration: animationDuration
			})
		}
	}else{
	// 没有参数直接使用navigateTo方式跳转,保留当前页面,跳转到应用内的某个页面
		uni.navigateTo({
			url: path,
			animationType: animationType,
			animationDuration: animationDuration
		})
	}
	
}
// 返回上一页
Vue.prototype.goBack = function() {
	uni.navigateBack({
		delta: 1
	});
}

encodeURIComponent是对参数进行编码,因为url有长度限制,太长的字符串会传递失败。 在获取参数的页面,再使用 decodeURIComponent进行解码即可。

3、案例演示

封装好了我们就来试试好不好使。

介绍一下我的案例:点击轮播图,跳转值轮播图的详情页(index.vue),携带图片和标题两个参数,并渲染在详情页面(detail.vue)。

index.vue文件:

这里只粘贴了部分轮播图组件代码,和所需要的数据。轮播图案例移步至:【uniapp小程序开发】—— 组件封装之【自定义轮播图】

<template>
<!-- 轮播图组件 -->
		<view class="px-3 py-2 ">
			<swiperDot class="position-relative" :current="current" :info="swipers">
			<!--
					swiper常用属性介绍:
						indicator-dots:轮播图正前方的小圆点(此案例没有使用官方提供的,是自定义的在右下角附近)
						autoplay:是否自动切换
						interval:图片轮播间隔此处为3秒
						duration:图片轮播动画时长 此处为0.5秒
						circular:是否开启无缝轮播(此处为到第三张图片后无缝播放第一张图片)
				 -->
				<swiper :autoplay="true" :interval="3000" :duration="500" circular style="height: 250rpx;"
					@change="changeIndicatorDots">
					<swiper-item v-for="(item,index) in swipers" :key="index" @click="goByPath('/pages/index/detail',{src:item.src,title:item.title})">
						<image :src="item.src" mode="sapectFill" style="height:250rpx;width: 100%;" class="rounded-lg">
			</image>
			</swiper-item>
		</swiper>
	</swiperDot>
	</view>
</template>
<script>
	import swiperDot from '@/components/comon/swiper-doc.vue'
	export default {
		components: {
			swiperDot
		},
		data() {
			return {
				current: 0, // 标识当前选中的图片序列号
				swipers: [{
					src: '/static/swiper/1.jpg',
					title: '自定义轮播图组件图片一'
				}, {
					src: '/static/swiper/2.jpg',
					title: '自定义轮播图组件图片二名字很长测试用'
				}, {
					src: '/static/swiper/3.jpg',
					title: '自定义轮播图组件图片三'
				}]
			}
		}
</script>

detail.vue文件

<template>
	<view>
		<view class="title">
			{{title}}
		</view>
		<image :src="src" mode="sapectFill" style="height:250rpx;width: 100%;"></image>
		<view>
			<!-- 调用封装好的goBack方法返回上一页 -->
			<button type="primary" @click="goBack">返回</button>
		</view>
	</view>
</template>

<script>
	import swiperDot from '@/components/comon/swiper-doc.vue'
	export default {
		components: {
			swiperDot
		},
		data() {
			return {
				src:''title:''
			}
		},
		onLoad(option) {
			// 打印传递过来的参数
			console.log(option)
			// decodeURIComponent将参数解码并使用JSON.parse() 方法用来解析JSON字符串转换为对象
			this.src = JSON.parse(decodeURIComponent(option.params)).src;
			this.title = JSON.parse(decodeURIComponent(option.params)).title;
		}
	}
</script>

效果图

在这里插入图片描述

最后

本文正在参加「金石计划 . 瓜分6万现金大奖」