From dd86e42113585cbc510e13a4e254f45c6e58c4b9 Mon Sep 17 00:00:00 2001 From: 2dowon Date: Wed, 18 Dec 2024 23:42:42 +0900 Subject: [PATCH] feat: implement hash router --- src/main.hash.js | 5 +++++ src/main.js | 2 +- src/utils/useRouter.js | 25 ++++++++++++++++++++----- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main.hash.js b/src/main.hash.js index 3ef381e0..cc7cb595 100644 --- a/src/main.hash.js +++ b/src/main.hash.js @@ -1 +1,6 @@ import "./main.js"; +import { useRouter } from "./utils/useRouter"; + +const { router } = useRouter("hash"); + +window.addEventListener("hashchange", () => router()); diff --git a/src/main.js b/src/main.js index 18b0e5a4..79558889 100644 --- a/src/main.js +++ b/src/main.js @@ -1,6 +1,6 @@ import { useRouter } from "./utils/useRouter"; -const { router } = useRouter(); +const { router } = useRouter("history"); window.addEventListener("load", () => router()); window.addEventListener("popstate", () => router()); diff --git a/src/utils/useRouter.js b/src/utils/useRouter.js index 9caf6036..aa45a80e 100644 --- a/src/utils/useRouter.js +++ b/src/utils/useRouter.js @@ -10,14 +10,16 @@ const PATHNAME_PAGE_MAP = { "/profile": () => renderProfilePage(), }; -export const useRouter = () => { +export const useRouter = (type) => { const routeGuard = (path) => { let pathname = path; const isLogin = useUserStore.isLogin(); - if (pathname === "/profile" && !isLogin) { - pathname = "/login"; - } else if (pathname === "/login" && isLogin) { + const refinedPathname = pathname.replace("#", ""); + + if (refinedPathname === "/profile" && !isLogin) { + pathname = `${type === "hash" ? "#" : ""}/login`; + } else if (refinedPathname === "/login" && isLogin) { pathname = "/"; } @@ -37,7 +39,20 @@ export const useRouter = () => { render(); }; - return { router: historyRouter }; + const hashRouter = (hash) => { + let newHash = hash || window.location.hash; + newHash = routeGuard(newHash); + + let render = PATHNAME_PAGE_MAP[newHash.replace("#", "")]; + if (!render) { + render = () => renderNotFoundPage(); + } + + history.pushState(null, "", newHash); + render(); + }; + + return { router: type === "history" ? historyRouter : hashRouter }; }; const renderMainPage = () => {