@codelet/core
Version:
mini core
37 lines (36 loc) • 1.24 kB
JavaScript
import { isString } from '@daysnap/utils';
import { definePlugin, getPageByPosition, parseLocation, parseQuery } from '../utils';
// 重写路由
export const router = definePlugin((col, options) => {
const { beforeEach, afterEach } = options || {};
const overwrite = (fn) => {
return async function (location) {
const to = isString(location) ? { url: location } : location;
const from = getCurrentRoute();
const next = async () => {
const options = parseLocation(to);
await fn(options);
afterEach?.(to, from);
};
if (beforeEach) {
await beforeEach(to, from, next);
}
else {
await next();
}
};
};
// 路由
Object.assign(col, {
useRouter: true, // 是否使用路由
redirectTo: overwrite(col.redirectTo),
navigateTo: overwrite(col.navigateTo),
reLaunch: overwrite(col.reLaunch),
switchTab: overwrite(col.switchTab),
});
});
function getCurrentRoute() {
const { route, options } = getPageByPosition();
const query = parseQuery(options);
return { url: `/${route}`, query };
}