// 对象转为路径参数 export const objToUrlParams = (obj) => { if (typeof obj === "string") return obj; let result = "?"; for (const element in obj) { result += `${element}=${obj[element]}&`; } return result.substring(0, result.length - 1); }; // 将字符串转为对象 export const urlParamsToObj = (url) => { const params = url.split("?")[1]; if (!params) return {}; const paramsArr = params.split("&"); const result = {}; paramsArr.forEach((item) => { const [key, value] = item.split("="); result[key] = value; }); return result; }; // 参数归一化路由参数 const normalizeParams = (url, options) => { let normalizeOptions = { url: "", }; if (typeof url === "string") { normalizeOptions = { url, ...options, }; } else { normalizeOptions = url; } const params = { redirected: getRoute().routeList[0].path, ...normalizeOptions.params, }; normalizeOptions.url += objToUrlParams(params); delete normalizeOptions.params; return normalizeOptions; }; // 路由映射表 export const router = { /** * 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。 */ push(url, options) { const normalizeOptions = normalizeParams(url, options); uni.navigateTo(normalizeOptions); }, /** * 关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */ redirectTo(url, options) { const normalizeOptions = normalizeParams(url, options); uni.redirectTo(normalizeOptions); }, /** * 关闭所有页面,打开到应用内的某个页面。 */ reLaunch(url, options) { const normalizeOptions = normalizeParams(url, options); uni.reLaunch(normalizeOptions); }, /** * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 */ switchTab(url, options) { const normalizeOptions = normalizeParams(url, options); uni.switchTab(normalizeOptions); }, /** * 关闭当前页面,返回上一页面或多级页面。 */ back() { const route = getRoute().routeList; if (route.length > 1) { uni.navigateBack(); return; } const { redirected, ...params } = route[0].params; if (redirected) { this.reLaunch({ url: `/${redirected}`, params, }); } }, }; // 获取当前路由参数 export const getRoute = () => { const pages = getCurrentPages(); const routeList = pages .map((item, index) => { // 处理路径乱码问题 // 解决乱码问题 for (const param in item.options) { item.options[param] = decodeURIComponent(item.options[param]); } return { params: item.options, path: item.route, index, }; }) .reverse(); return { routeList, params: routeList[0].params, }; };