uniapp关于跳转页面的封装

 uni-app路由跳转实现这样一个功能:

  1. 实现页面跳转
  2. 保存历史路径

一、在utill文件中新建一个pagaChange.ts文件

代码如下: 

const pageChange = (method, route) => {
	if (uni.getStorageInfoSync('beforePage')) {
		const beforePage = getCurrentPages()[getCurrentPages().length - 1].route;
		let current = beforePage.split('/');
		let routeCurrent = route.split('/');
		let backNum = routeCurrent.reduce((obj, cur) => {
			(cur in obj) ? obj[cur]++ : obj[cur] = 1;
			return obj
		}, {})['..'];
		routeCurrent = current.splice(0,current.length -  backNum-1 ).concat(routeCurrent.slice(backNum)).join('/');
		uni.setStorageSync('beforePage', beforePage);
		uni.setStorageSync('currentPage', routeCurrent);
	}
	if (method == 'navigateTo') {
		uni.navigateTo({
			url: route
		});
	}
	// 关闭当前页面,跳转
	if (method == 'redirectTo') {
		uni.redirectTo({
			url: route
		});
	}
	// 关闭所有页面直接跳转
	if (method == 'reLaunch') {
		uni.reLaunch({
			url: route
		});
	}
	// 跳转tabBar页面
	if (method == 'switchTab') {
		uni.switchTab({
			url: route
		});
	}
};

export default pageChange;
const pageChange = (method, route) => {
	if (uni.getStorageInfoSync('beforePage')) {
		const beforePage = getCurrentPages()[getCurrentPages().length - 1].route;
		let current = beforePage.split('/');
		let routeCurrent = route.split('/');
		let backNum = routeCurrent.reduce((obj, cur) => {
			(cur in obj) ? obj[cur]++ : obj[cur] = 1;
			return obj
		}, {})['..'];
		routeCurrent = current.splice(0,current.length -  backNum-1 ).concat(routeCurrent.slice(backNum)).join('/');
		uni.setStorageSync('beforePage', beforePage);
		uni.setStorageSync('currentPage', routeCurrent);
	}
	if (method == 'navigateTo') {
		uni.navigateTo({
			url: route
		});
	}
	// 关闭当前页面,跳转
	if (method == 'redirectTo') {
		uni.redirectTo({
			url: route
		});
	}
	// 关闭所有页面直接跳转
	if (method == 'reLaunch') {
		uni.reLaunch({
			url: route
		});
	}
	// 跳转tabBar页面
	if (method == 'switchTab') {
		uni.switchTab({
			url: route
		});
	}
};

export default pageChange;

二、将方法挂载全局

uniapp关于跳转页面的封装_第1张图片

三、使用场景

 uniapp关于跳转页面的封装_第2张图片

四、获得当前页面信息

uni.getStorageInfoSync('beforePage')

uni.getStorageInfoSync('currentPage')

 

你可能感兴趣的:(uniapp,uni-app,微信小程序,前端)