当前位置: 首页 > news >正文

uniapp h5地址前端重定向跳转

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

ps:只能在h5中使用

首先需要用到query-string
安装query-string

npm install query-string --save
//or
yarn add query-string

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

const routeMap = {"/home":{path:'/pages/home/index',isTab:true}
}
export default routeMap;

需要用到的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页面中使用

import matchAndNavigate from "@/router-map/router-map";
onLaunch:function(){matchAndNavigate();
}
http://www.lryc.cn/news/484869.html

相关文章:

  • uniapp隐藏自带的tabBar
  • 使用--log-file保存pytest的运行日志
  • WebAPI性能监控-MiniProfiler与Swagger集成
  • 视频会议接入GB28181视频指挥调度,语音对讲方案
  • 深度学习和图像处理
  • 〔 MySQL 〕数据类型
  • 云安全之云计算基础
  • PostgreSQL pg-xact(clog)目录文件缺失处理
  • 《ElementPlus 与 ElementUI 差异集合》Icon 图标 More 差异说明
  • 基于碎纸片的拼接复原算法及MATLAB实现
  • 苍穹外卖 软件开发流程
  • mysqldump导出表结构和表数据和存储过程和函数
  • 常见的排序算法及分类对比
  • 多窗口切换——selenium
  • LFD STM32编程规范20241111
  • Python学习------第八天
  • 【扩散——BFS】
  • C++ 编程基础(5)类与对象 | 5.5、多态
  • 客户端发送http请求进行流量控制
  • STM32 低功耗模式详解
  • 我的第一个PyQt5程序
  • Unity调用Python
  • 前端,location.reload刷新页面
  • 5G的发展演进
  • 数据库参数备份
  • PG数据库 数据库时间字段 开始时间和结束时间,判断和查询条件的开始和截止时间存在交集,SQL如何编写
  • k8s服务内容滚动升级以及常用命令介绍
  • 机器学习: LightGBM模型(优化版)——高效且强大的树形模型
  • Wordpress常用配置,包括看板娘跨域等
  • Python学习从0到1 day27 Python 高阶技巧 ③ 设计模式 — 单例模式