ruoyi-plus-soybean/src/composables/common/router.ts

91 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-01-05 01:35:32 +08:00
import { unref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import type { RouteLocationRaw } from 'vue-router';
import { router as globalRouter } from '@/router';
import { useRouteStore } from '@/store';
import { LoginModuleKey } from '@/interface';
/**
*
* @param inSetup - vue页面/setup里面调用axios里面无法使用useRouter和useRoute
*/
export function useRouterPush(inSetup: boolean = true) {
const { getRouteName } = useRouteStore();
const router = inSetup ? useRouter() : globalRouter;
const route = inSetup ? useRoute() : unref(globalRouter.currentRoute);
/**
*
* @param to -
* @param newTab - Tab标签打开
*/
function routerPush(to: RouteLocationRaw, newTab = false) {
if (newTab) {
const routerData = router.resolve(to);
window.open(routerData.href, '_blank');
} else {
router.push(to);
}
}
/** 返回上一级路由 */
function routerBack() {
router.go(-1);
}
/**
*
* @param newTab -
*/
function toHome(newTab = false) {
routerPush(getRouteName('root'), newTab);
}
/**
*
* @param loginModule -
* @param redirectUrl - (),undefined表示取当前地址为重定向地址
*/
function toLogin(loginModule?: LoginModuleKey, redirectUrl?: string) {
const module: LoginModuleKey = loginModule || 'pwd-login';
const routeLocation: RouteLocationRaw = {
name: getRouteName('login'),
params: { module }
};
const redirect = redirectUrl || route.fullPath;
Object.assign(routeLocation, { query: { redirect } });
routerPush(routeLocation);
}
/**
*
* @param module -
*/
function toLoginModule(module: LoginModuleKey) {
const { query } = route;
routerPush({ name: getRouteName('login'), params: { module }, query });
}
/**
*
* @param redirect -
*/
function toLoginRedirect(redirect?: string) {
if (redirect) {
routerPush(redirect);
} else {
toHome();
}
}
return {
routerPush,
routerBack,
toHome,
toLogin,
toLoginModule,
toLoginRedirect
};
}