first commit
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
export type Route = {
|
||||
path: string;
|
||||
view: () => HTMLElement;
|
||||
};
|
||||
|
||||
export class Router {
|
||||
private routes: Route[];
|
||||
private outlet: HTMLElement;
|
||||
|
||||
constructor(outlet: HTMLElement, routes: Route[]) {
|
||||
this.routes = routes;
|
||||
this.outlet = outlet;
|
||||
window.addEventListener('popstate', () => this.resolve());
|
||||
}
|
||||
|
||||
navigate(path: string) {
|
||||
window.history.pushState({}, '', path);
|
||||
this.resolve();
|
||||
}
|
||||
|
||||
resolve() {
|
||||
const path = window.location.pathname;
|
||||
const match = this.routes.find((r) => r.path === path);
|
||||
this.outlet.innerHTML = '';
|
||||
this.outlet.append(
|
||||
match ? match.view() : document.createElement('not-found-page')
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user