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

🍍前言

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

🍋正文

1、看官网

1.1 navigator API 介绍

页面跳转。

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

该组件的功能有API方式另见https://uniapp.dcloud.io/api/router?id=navigateto

属性说明

属性名类型默认值说明平台差异说明
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-typeopen-typenavigatenavigateBack 时有效窗口的显示/关闭动画效果。
  • animation-duration窗口显示/关闭动画的持续时间。

2.2、封装代码

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

// openType 默认值为 navigateanimationType 默认值为pop-inanimationDuration 默认值为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>

效果图

在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

“【uniapp小程序】路由跳转navigator传参封装_小程序跳转 封装” 的相关文章