1. 필요한 함수 선언
// router.ts
export const push = (nextUrl: string) => {
window.dispatchEvent(
new CustomEvent('route-push', {
detail: {
nextUrl,
},
}),
);
};
// router.ts
export const pushRouter = (onRoute: () => void) => {
window.addEventListener(ROUTE_PUSH_EVENT_NAME, (e: CustomEventType) => {
const { nextUrl } = e.detail;
if (nextUrl) {
history.pushState(null, null, nextUrl);
onRoute();
}
});
};
// routes.ts
const route = (target: Element) => {
const { pathname } = window.location;
switch (pathname) {
case '/':
new Home(target);
break;
case '/HexColors':
new HexColors(target);
break;
case '/RandomQuotes':
new RandomQuotes(target);
break;
default:
console.log('not found page');
}
};
2. 처음 app이 실행 될 때 전역 객체에 이벤트를 등록해주기 위해 App컴포넌트에 router함수를 실행시킨다
// App.ts
...
setInitRouter(target: Element) {
router(target);
pushRouter(() => {
router(target);
});
replaceRouter(() => {
router(target);
});
popStateRouter(() => {
router(target);
});
}
mounted() {
...
this.setInitRouter($main);
}
3. url이동이 필요한 경우 push함수를 불러와 실행시킨다
handleClickContent(e: Event) {
console.log('handler');
const { target } = e;
if (target instanceof HTMLElement) {
const { url } = target.dataset;
push(url);
}
}
문제점
devServer로 브라우저 실행 시 라우터로 url을 이동했을 때 Cannot GET문구가 뜨면서 제대로 동작하지 않았다
해결책
// webpack.config.js
module.exports = {
...
output: {
...
publicPath: '/'
},
devServer: {
historyApiFallback: true, // 이걸 추가해줘야 했음
},
}