Router
The Router
class provides a simple way to create a router for your SPA application.
Installation
Section titled “Installation”Metro UI already includes the Router
library.
You can use it without any additional installation, but if you want to use it in your project, you can install it with package manager:
npm install @olton/router
pnpm install @olton/router
yarn add @olton/router
or use CDN:
<script type="module"> import Router from "https://esm.run/@olton/router";</script>
import { Router } from "@olton/router";
const router = new Router()
router.addRoute("/", () => { console.log("Home page")})router.addRoute("/product/:id", (params) => { console.log(`Product page for product ${params.id}`)})
router.listen()
Options
Section titled “Options”Option | Type | Description |
---|---|---|
base | string | Base URL for the router. Default is / . |
fallback | string | Fallback route. Default is / |
maxRedirects | number | Maximum redirects. Default is 5 . |
useCache | boolean | Enabling cache. |
cahceLimit | number | Cache size. Default is 50 . |
enableSwipeNavigation | boolean | Enable swipe left/right for history navigation. Default is false . |
routes | object | Create routes in constructor. Default is null . |
plugins | array | Registering plugins in constructor. Default is null . |
const router = new Router({ base: "/", fallback: "/", maxRedirects: 5, cacheLimit: 50, enableSwipeNavigation: false, routes: { "/": () => { }, "/product/:id": (params) => { } }})
Routes
Section titled “Routes”Add routes
Section titled “Add routes”To add routes, you can use methods:
addRoute(path, callback)
- add a new routeaddNestedRoute(parentPath, path, callback)
- add a nested routeaddLazyRoute(path, callback)
- add a lazy routeaddLazyNestedRoute(parentPath, path, importFunc)
- add a lazy nested routeaddFallbackRoute(path)
- add a fallback routeadd404Route(path)
- add a 404 routeaddErrorRoute(path)
- add a error routeaddProtectedRoute(path, callback, guardFunction, fallback = '/login')
- add a protected route
router.addRoute("/", () => { })router.addRoute("/product/:id", (params) => { })
Remove routes
Section titled “Remove routes”To remove a route, use the removeRoute(path)
method:
router.removeRoute("/product/:id")
Update routes
Section titled “Update routes”To update a route, use the updateRoute(path, callback)
method:
router.updateRoute("/product/:id", (params) => { })
Manual navigation
Section titled “Manual navigation”Router uses method navigate(path)
to navigate to a matched route.
For manual navigation, you can use the navigateTo(path, replaceState = false)
router.navigateTo("/product/1")
Listen for routes
Section titled “Listen for routes”To listen for routes, use the listen()
method:
router.listen()
Get current route
Section titled “Get current route”To get the current route, use the current
property:
const currentRoute = router.current
Get routes
Section titled “Get routes”To get all routes, use the routes
property or getRoutes()
method:
const allRoutes = router.routesconst allRoutes = router.getRoutes()
Middleware
Section titled “Middleware”You can use middleware to intercept requests and perform actions before the route is processed. To add middleware, use the use(middleware)
method:
router.use((route) => { console.log(`Navigating to ${route.path}`)})
You can use hooks to perform actions before and after the route is processed. To add hooks, use the beforeEach(hook)
and afterEach(hook)
methods:
Before each hook
Section titled “Before each hook”router.beforeEach((route) => { console.log(`Before navigating to ${route.path}`)})
After each hook
Section titled “After each hook”router.afterEach((route) => { console.log(`After navigating to ${route.path}`)})
Redirects
Section titled “Redirects”You can use redirects to redirect from one route to another. To add a redirect, use the addRedirect(from, to)
method:
router.addRedirect("/old-path", "/new-path")
Test path
Section titled “Test path”You can test a path, with a test(path)
method. This method returns object:
{ "original": string, // original path "sanitized": string, // sanitized path "isBlocked": boolean, // must blocked "isModified": boolean, // was modified}
router.test("/product/1")
You can use cache to store routes. To enable cache, use the useCache
option in the constructor:
const router = new Router({ useCache: true})
To set the cache limit, use the cacheLimit
option in the constructor:
const router = new Router({ cacheLimit: 100})
To clear the cache, use the clearCache()
method:
router.clearCache()
You can enable debug mode with debug
option. This will log all routes and navigation events to the console:
const router = new Router({ debug: true})
Plugins
Section titled “Plugins”You can use plugins to extend the functionality of the router.
// Пример плагина логированияconst loggerPlugin = { install(router, options = {}) { const prefix = options.prefix || '[Router]'; const level = options.level || 'info';
// Подписываемся на события роутера router.on('beforeNavigate', (route) => { console[level](`${prefix} Переход на: ${route.path}`); });
router.on('error', (error) => { console.error(`${prefix} Ошибка:`, error); }); },
onInit(router) { console.log('Logger plugin initialized'); },
onDestroy() { console.log('Logger plugin destroyed'); }};
// Использованиеconst router = new Router({ plugins: [ loggerPlugin, ]});
// orrouter.usePlugin(loggerPlugin, { prefix: '[MyApp Router]', level: 'debug' });