123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- // 对象转为路径参数
- 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,
- };
- };
|