如何创建中间件或如何管理前端和管理员的以下路由

How to create a middleware or how to manage the below route for front end and admin

如何通过 Vue 中的中间件管理前面板和管理面板的 url。

这是我在router/index.js 文件中编写的代码:

const router = new VueRouter({ mode: 'history', routes });

  router.beforeEach((to, from, next) => {

  // redirect to login page if not logged in and trying to access a restricted page
  const loggedIn = localStorage.getItem('usertoken') == null ? false : true;
  const user = JSON.parse(localStorage.getItem('user'));

  //this is for admin
  next('/admin/login')
  next('/admin/home');

  //this is my front URL
  next('/terms-condition');
  next('/home');
  next()
})
export default router;

你的实现方式是正确的

一旦用户成功登录,使用 if else 条件重定向到管理面板,也使用 vue-router 中提供的 Navigation guards

https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard

这有助于防止其他用户直接使用此 url

看下面的代码或许对你有帮助

/** * 认证中间件 */

router.beforeEach((to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
  const loggedIn = localStorage.getItem('usertoken') == null ? false : true;
  const user = JSON.parse(localStorage.getItem('user'));

  if (to.meta.portal == 'admin') {
    if (to.meta.auth) {
        if (!loggedIn) {
            next('/admin/login')
        } else if (loggedIn) {
            next();
        }
    } else {
        if (!loggedIn) {
            next();
        } else if (loggedIn) {
            if (user.role_id == '1') {
                next('/admin/home');
            } else {
                next('/');
            }
        }

    }
  } else if (to.meta.portal == 'front') {

    if (loggedIn) {

        if (user.role_id == '1') {
            next('/admin/home');
        } else {
            next('/');
        }

    } else if (!loggedIn) {
        if (to.path == "/admin") {
            next('/admin/login');
        } else {
            next();
        }
    }
  }
 next()
})

export default router;

并且您需要创建两个路由器文件,一个用于前台,另一个用于管理员:

//前面的路由文件看起来像

export default [{
path: '/',
meta: { auth: false, portal: 'front' },
component: () => import('@/components/layouts/front/main.vue'),
children: [
    {
        path: '/',
        name: 'front-home',
        title: 'Dashboard',
        meta: { auth: false, portal: 'front' },
    }
   ]
}]

//admin 路由器文件会像

export default [
 {
    path: 'user',
    name: 'users',
    title: 'Users',
    meta: { auth: true, portal: 'admin' },
    component: () => import('@/components/templates/admin/user'),
 }
]

主要区别在于定义哪个门户将通过相应 route.Without 门户访问的门户在 meta 中不起作用。