Vue2在刷新任何页面时会重定向到主页

时间:2019-04-24 05:47:12

标签: javascript vuejs2 vuex vue-router

我正在尝试研究vue2。我面临一个奇怪的问题。 我有4条路线。

  1. /未登录用户时登录,他们将看到此页面,因此他们可以登录。
  2. /当用户登录时将其上传到该页面。
  3. /培训此页面以进行其他工作
  4. / documents / collaboration当他们使用此路由器时,它应该仅呈现火车组件,但url为BASE_URL / documents / collaborate

我的问题是,当我刷新/ 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;  

1 个答案:

答案 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();
})