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();
}
相关推荐
SailingCoder1 天前
【 从“打补丁“到“换思路“ 】一次企业级 AI Agent 的架构拐点
大数据·前端·人工智能·面试·架构·agent
~央千澈~1 天前
抖音弹幕游戏开发之第12集:添加冷却时间机制·优雅草云桧·卓伊凡
java·服务器·前端
CappuccinoRose1 天前
CSS 语法学习文档(十三)
前端·css·学习·postcss·模块化·预处理器
OpenTiny社区1 天前
Angular Module→Standalone 架构进化解析
前端·架构·angular.js
哆啦A梦15881 天前
Vue3魔法手册 作者 张天禹 06_监控
前端·vue.js·typescript
恋猫de小郭1 天前
你知道不,你现在给 AI 用的 Agent Skills 可能毫无作用,甚至还拖后腿?
前端·人工智能·ai编程
用户600071819101 天前
【翻译】用生成器实现可续充队列
前端
少云清1 天前
【UI自动化测试】4_web自动化测试 _元素定位(重点)
前端·web前端自动化
若丶相见1 天前
腾讯云完整部署方案:CODING + CI/CD + Docker + Nginx + K8s 扩展
前端·后端
比奇堡鱼贩1 天前
python第五次作业
开发语言·前端·python