我正在尝试研究vue2。我面临一个奇怪的问题。 我有4条路线。
我的问题是,当我刷新/ train页面或粘贴协作网址时,它会将我重定向到/ uploads。
我不知道这有什么问题以及为什么会这样。
下面是我的router.js的代码
import Vue from 'vue'
import Router from 'vue-router'
import LoginPage from './views/Login.vue'
import Uploads from './views/Uploads.vue'
import Train from "./views/Train";
Vue.use(Router)
export const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/login',
name: 'login',
component: LoginPage,
meta: {bodyClass: 'auth-wrapper'}
},
{
path: '/', redirect: '/uploads'
},
{
path: "/uploads",
name: 'Uploads',
component: Uploads,
meta: {bodyClass: 'full-screen', verboseName: 'Data Classifier', icon: '@/assets/img/company5.png'}
},
{
path: "/train",
name: 'Train',
component: Train,
meta: {bodyClass: 'full-screen', verboseName: 'Data Trainer', icon: '@/assets/img/company5.png'}
},
{
path: "/documents/collaborate/:id",
name: "Collaborate",
component: Train,
meta: {bodyClass: 'full-screen', verboseName: 'Data Trainer', icon: '@/assets/img/company5.png'}
}
]
})
router.beforeEach((to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const publicPages = ['/login'];
const authRequired = !publicPages.includes(to.path);
const loggedIn = localStorage.getItem('user-token');
if (authRequired && loggedIn === null) {
return next('/login');
}
if (loggedIn !== null && !authRequired) {
return next('/uploads');
}
next()
})
export default router;
答案 0 :(得分:0)
由于/uploads
中的if (loggedIn !== null && !authRequired) {...}
条件为 true ,因此重定向到route.beforeEach()
。更改:
router.beforeEach((to, from, next) => {
...
if (authRequired && loggedIn === null) {
return next('/login');
}
// navigate to to.path() page
next();
})