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();
}
相关推荐
Mh1 小时前
别再只会 `find` 了:Map 在前端业务里的真实用法
前端·javascript
陈随易2 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
爱丶狸2 小时前
Grafana_Zabbix_ImageRenderer_部署与前端操作手册
linux·前端·zabbix·grafana·kylin
用户059540174465 小时前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
kyriewen5 小时前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜5 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉5 小时前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token
码云之上6 小时前
AI Agent 工程化总览篇:从 Prompt 到 Harness
前端·人工智能
2501_926978336 小时前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作
IT_陈寒6 小时前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端