0.0.14 • Published 9 months ago
@ncpa0cpl/vrouter v0.0.14
VRouter
A framework independent router for JavaScript.
Basic Usage
import { router } from "@ncpa0cpl/vrouter";
import { renderAboutUsPage, renderHomePage } from "./pages";
// define the routes
const AppRouter = router({
paramNames: [],
subroutes: (define) => ({
home: define({
paramNames: [],
title: "Home Page",
default: true,
component() {
return renderHomePage(); // return a HTMLElement
},
}),
about: define({
paramNames: [],
title: "About Us",
component() {
return renderAboutUsPage(); // return a HTMLElement
},
}),
}),
});
// mount the router on the page
document.body.appendChild(AppRouter.rootElement());
// navigate to the about us page
AppRouter.nav.about.$open();Query Parameters (slugs)
// define a route with a arbitrary string in the URL
const AppRouter = router({
paramNames: [],
subroutes: (define) => ({
posts: define({
paramNames: [],
subroutes: (define) => ({
postID: define({
slug: true,
component(ctx) {
const slugValue = ctx.slug.get();
// listen to slug changes
ctx.slug.add(() => {
console.log(ctx.slug.get());
});
return renderPostPage();
},
}),
}),
}),
}),
});
// navigate to the post page
AppRouter.nav.posts.postID("123").$open();Search Parameters
// define a route with search parameters
const AppRouter = router({
paramNames: [],
subroutes: (define) => ({
search: define({
searchParams: ["q"],
component(ctx) {
const searchValue = ctx.params.get().q;
// listen to search parameter changes
ctx.params.add(({ q }) => {
console.log(q);
});
return renderSearchPage();
},
}),
}),
});
// navigate to the search page
AppRouter.nav.search.$open({ q: "search query" });Replace routes and Nested routes
Routes defined in the router can have one of two modes, replace or nest-routes. A replace mode route will replace its Element with the active child Route if there is one, while a nest-routes mode route will append the active child Route Element to a outlet Element, which can be accessed through the Route context.
const AppRouter = router({
paramNames: [],
mode: "nest-routes",
component(ctx) {
const layout = document.createElement("div");
layout.append(ctx.out()); // append the Outlet Element to the layout div
return layout;
},
subroutes: (define) => ({
home: define({
paramNames: [],
title: "Home Page",
default: true,
component() {
const homeContainer = document.createElement("div");
// this div will be appended to the layout div created above when this route is opened
return homeContainer;
},
}),
}),
});