当前位置:网站首页>Application of global route guard

Application of global route guard

2022-06-25 10:54:00 Stranger & love sorrow

Front routing guard router.beforeEach

Determine whether the page needs to log in

1 Set... In the route meta isToken The page used to determine whether you need to log in to enter

{
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: ' Sign in ',
      isToken: false
    },
  },

2 The front guard judges

router.beforeEach((to, from, next) => {
 //  obtain token
  let token = localStorage.getItem('token')
  if (token && token != 'null') {  // Yes token   release 
    next()
  } else {
   //  Determine whether the page needs to be logged in 
    if (to.meta.isToken) {  // by true  Indicates a page that can only be accessed after login 
      Toast(' Please log in first ');
   //  Return to login page 
      next('/login')
    } else {
      next()
    }
  }
})

Post route hook  router.afterEach

Set dynamic title

1 Pictured above , Set up meta Inside title attribute

meta: {
      title: ' Sign in ',
      isToken: false
    },

2 Post route guard settings

router.afterEach((to, from, next) => {
  document.getElementById('titleId').innerHTML = to.meta.title
})

Global analysis guard  router.beforeResolve

  Before the navigation is confirmed , At the same time, after guard and asynchronous routing components in all components are resolved , Parse guard is called

原网站

版权声明
本文为[Stranger & love sorrow]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200542263031.html