uniapp h5地址前端重定向跳转

简单说下功能,就是在地址输入http://localhost:8080/home 会自行跳转到http://localhost:8080/pages/home/index,如果有带参数的话也会携带上去。

ps:只能在h5中使用

首先需要用到query-string

安装query-string

js 复制代码
npm install query-string --save
//or
yarn add query-string

创建一个路由映射的js集合(自行命名)

router-map.js

js 复制代码
const routeMap = {
	"/home":{
		path:'/pages/home/index',
		isTab:true
	}
}
export default routeMap;

需要用到的js

js 复制代码
import routeMap from "./router-map";
import queryString from 'query-string';

// 解析当前URL,返回路径和查询字符串
function getCurrentUrl() {
	const url = window.location.pathname + window.location.search;
	let [path, searchString = ""] = url.split("?");
	return { path, searchString };
}

// 构建完整的URL
function buildUrl(pagePath, queryString) {
	return queryString ? `${pagePath}?${queryString}` : pagePath;
}

// 匹配当前URL并导航
async function matchAndNavigate() {
	const { path, searchString } = getCurrentUrl();
	let routeInfo = routeMap[path]; // 尝试直接匹配静态路由
	var query = queryString.parse(searchString)
	// 检查是否有动态路由匹配
	if (!routeInfo) {
		Object.keys(routeMap).forEach((pattern) => {
			if (pattern.includes(":")) {
				const regex = new RegExp(
					`^${pattern.replace(/:([^\s/]+)/g, "(?<$1>[\\w-_]+)")}$`
				);
				const match = path.match(regex);
				if (match) {
					// 正确复制路由信息并替换动态部分
					routeInfo = { ...routeMap[pattern] }; // 复制对象,避免修改原始映射
					routeInfo.path = routeInfo.path.replace(
						/:[^\s/]+/,
						match[1]
					);
					if (match.groups) {
						query = { ...match.groups, ...query }
					}
				}
			}
		});
	}

	// 执行跳转
	if (routeInfo && routeInfo.path) {
		const finalUrl = buildUrl(routeInfo.path, queryString.stringify(query));
		await uni.preloadPage({ url: finalUrl });
		if (routeInfo.isTab) {
			uni.switchTab({
				url: finalUrl,
			});
		} else {
			uni.redirectTo({
				url: finalUrl,
			});
		}
	} else {
		// 适当的错误处理或默认处理
	}
}

export default matchAndNavigate;

在app.vue页面中使用

js 复制代码
import matchAndNavigate from "@/router-map/router-map";
onLaunch:function(){
	matchAndNavigate();
}
相关推荐
mCell4 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip4 小时前
Node.js 子进程:child_process
前端·javascript
excel7 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel9 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼10 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping10 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙11 小时前
[译] Composition in CSS
前端·css
白水清风11 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix11 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780011 小时前
new、原型和原型链浅析
前端·javascript