Vue.js Authentication + Navigation Guard

강정우·2023년 4월 6일
0

vue.js

목록 보기
35/72
post-thumbnail

특정 페이지 막기

  • 만약 로그인도 안 했는데 특정 글쓰기 페이지라든지, admin 페이지를 접근하면 곤란하다. 그래서 앞서 배운 것들을 종합하여 로직을 만들어보고자 한다.

router.js

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/coaches' },
    { path: '/coaches', component: CoachesList },
    {
      path: '/coaches/:id',
      component: CoachDetail,
      props: true,
      children: [
        { path: 'contact', component: ContactCoach } // /coaches/c1/contact
      ]
    },
    { path: '/register', component: CoachRegistation, meta:{requireAuth:true} },
    { path: '/requests', component: RequestsReceived, meta:{requireAuth:true} },
    { path: '/auth', component: UserAuth, meta:{requireUnauth:true}},
    { path: '/:notFound(.*)', component: NotFound }
  ]
});

router.beforeEach(function (to, from, next){
  if(to.meta.requireAuth && !store.getters.isAuthenticated){
    next('/auth');
  }else if(to.meta.requireUnauth&&store.getters.isAuthenticated){
    next('/coaches');
  }else{
    next();
  }
})

export default router;
  • 여기서 store는 수동으로 import해와야한다!!
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글