vbv/client/src/router/history.ts

35 lines
920 B
TypeScript

// handle route history
import type {
NavigationGuard,
RouteLocationNormalized,
RouteLocationRaw,
Router,
} from "vue-router";
const routeHistory: RouteLocationNormalized[] = [];
const MAX_HISTORY = 10; // for example, store the last 10 visited routes
let isFirstNavigation = true;
export const addToHistory: NavigationGuard = (to, from, next) => {
// Add the current route to the history, and ensure it doesn't exceed the maximum length
if (isFirstNavigation) {
isFirstNavigation = false;
} else {
routeHistory.push(from);
}
if (routeHistory.length > MAX_HISTORY) {
routeHistory.shift();
}
next();
};
export function routerBackOrFallback(router: Router, fallbackRoute: RouteLocationRaw) {
// Check the latest route in history
const previousRoute = routeHistory[routeHistory.length - 1];
if (previousRoute) {
router.back();
} else {
router.push(fallbackRoute);
}
}