vue-vben-admin/src/hooks/web/usePage.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-04-10 19:25:49 +08:00
import type { RouteLocationRaw, Router } from 'vue-router';
2020-09-28 20:19:10 +08:00
import { PageEnum } from '/@/enums/pageEnum';
import { isString } from '/@/utils/is';
import { unref } from 'vue';
2021-04-10 19:25:49 +08:00
import { useRouter } from 'vue-router';
import { REDIRECT_NAME } from '/@/router/constant';
2020-12-03 21:49:32 +08:00
export type RouteLocationRawEx = RouteLocationRaw & { path: PageEnum };
2020-09-28 20:19:10 +08:00
function handleError(e: Error) {
console.error(e);
}
// page switch
2021-04-10 19:25:49 +08:00
export function useGo(_router?: Router) {
let router;
if (!_router) {
router = useRouter();
}
const { push, replace } = _router || router;
2020-10-18 21:55:21 +08:00
function go(opt: PageEnum | RouteLocationRawEx | string = PageEnum.BASE_HOME, isReplace = false) {
2021-04-10 19:25:49 +08:00
if (!opt) {
return;
}
2020-09-28 20:19:10 +08:00
if (isString(opt)) {
isReplace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
} else {
const o = opt as RouteLocationRaw;
isReplace ? replace(o).catch(handleError) : push(o).catch(handleError);
}
}
return go;
}
/**
* @description: redo current page
*/
2021-04-10 19:25:49 +08:00
export const useRedo = (_router?: Router) => {
const { push, currentRoute } = _router || useRouter();
const { query, params = {}, name, fullPath } = unref(currentRoute.value);
2020-12-15 00:13:23 +08:00
function redo(): Promise<boolean> {
return new Promise((resolve) => {
if (name === REDIRECT_NAME) {
resolve(false);
return;
}
if (name && Object.keys(params).length > 0) {
params['_redirect_type'] = 'name';
params['path'] = String(name);
} else {
params['_redirect_type'] = 'path';
params['path'] = fullPath;
}
push({ name: REDIRECT_NAME, params, query }).then(() => resolve(true));
2020-09-28 20:19:10 +08:00
});
}
return redo;
};