如何通过Vue中的Middleware管理前面板和管理面板的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;
请参见下面的代码,可能会对您有所帮助
/ ***用于认证的中间件* /
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'),
}
]
主要区别是门户网站,该门户网站定义了将通过相应的路由访问的门户网站。没有在meta内的门户网站将无法使用。
您实施的方法是正确的
一旦用户成功登录,使用if else条件重定向到管理面板,也使用vue-router中给定的导航卫士
https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard
此帮助防止其他用户直接使用此网址