Skip to main content
 首页 » 编程设计

vue-router封装和用户是否需要登录

2022年07月15日149Renyi-Fan
vue-router封装和用户是否需要登录 
 
import Vue from 'vue' 
import Router from 'vue-router' 
 
Vue.use(Router) 
const routes = [{ 
  path: '/', 
  redirect: '/home' 
  }, 
  { 
    path: '/home', 
    name: 'home', 
    component: () =>import('./views/Home.vue'), 
    meta: { 
      requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的 
    }, 
    children: [{ 
      path: '/account_management', 
      name: 'account_management', 
      component: () =>import('./views/admin/account_management.vue') 
    }] 
 
  }, 
  { 
    path: '/login', 
    name: 'login', 
    component: () => 
    import('./views/login/login.vue') 
  } 
 
]
export default  new Router({
  routes 
}) 
 
//路由拦截器写到mian.js 
router.beforeEach((to, from, next) => {
  const username = Cookies.get('username');
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    if (username) { // 判断本地是否存在username
      next()
    } else {
      // 未登录,跳转到登陆页面
      next({
        path: '/'
      })
    }
  } else {
    next();
  }
})

本文参考链接:https://www.cnblogs.com/wulicute-TS/p/14749855.html