VUE
[VUE] 특정 페이지 이동 전 로그인 여부 검사하기(라우터 Router beforeEach) 네비게이션가드
hobbada
2022. 10. 5. 12:09
router의 beforeEach 를 활용하면 된다.
const routes = [
{
path: "/",
component: () => import("layouts/MainLayout.vue"),
children: [
{
path: "",
component: () => import("pages/Index.vue"),
meta: { requiresAuth: false },
},
{
path: "/auth",
component: () => import("pages/Auth.vue"),
meta: { requiresAuth: true },
},
],
},
];
export default routes;
route.js 에 로그인이 필요한 페이지는 meta 값에 true를 넣어준다.
Router.beforeEach(function (to, _, next) {
const access_token = getItem("accesToken");
if (!access_token) {
if (to.meta.requiresAuth) {
alert("로그인 후 이용해주세요.");
next("/login");
} else {
next();
}
} else {
next();
}
});
Router의 index.js
로그인 이 후에, 어딘가에 token을 저장한 후. router가 돌기 전 토큰 보유 여부를 검사하고
토큰이 없는데, meta값이 true 인 페이지를 접근하려하면 해당 부분에 처리를 하면 된다.
반응형