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();
}
相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60617 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅8 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax