繁体   English   中英

Vue Router Auth Guard url 额外字符

[英]Vue Router Auth Guard url Extra Charcters

我在每个函数之前使用 Vue 路由 Auth Guard。 如果用户未登录,他将无法访问仪表板和个人资料页面。 它工作正常,但是当我强行尝试路由时,它会阻止我,但还会在 url 中添加一些额外的字符。 我能不能去掉那些。

url - http://localhost:8080/?redirect=%2Fdashboard

import Vue from 'vue'
import Router from 'vue-router'
import * as firebase from "firebase";

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes : [
    {
      path: '/',
      name: 'home',
      component: () => import('../components/home')
    },
    {
      path: '/login',
      name: 'signin',
      component: () => import('../components/user/signIn')
    },
    {
      path: '/register',
      name: 'signup',
      component: () => import('../components/user/signUp')
    },
    {
      path: '/forgot-password',
      name: 'forgotPassword',
      component: () => import('../components/user/forgotPassword')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../components/user/profile'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('../components/dashboard'),
      meta: {
        requiresAuth: true
      }
    },

  ]
})

//Router Guard
router.beforeEach((to, from, next) => {
  // Check fore required auth guard
  if(to.matched.some(record => record.meta.requiresAuth)){
    // check if not logged in
    if(!firebase.auth().currentUser){
      // go to login
      next({
        path: '/',
        query: {
          redirect: to.fullPath
        }
      });
    }else{
      // proceed to route
      next();
    }
  }else{
    next();
  }
})

export default router

当用户未登录时,路由器守卫重定向到path: '/', query: {redirect: to.fullPath} 此时to.fullPath == "/dashboard"

正斜杠'/'字符不是有效的查询字符,因此 vue-router 使用encodeURIComponent("/dashboard")将其转换为编码版本%2F

当用户登录时,您可以从$route.query.redirect获取重定向参数,它会自动解码回/dashboard

或者,由于您的所有路由都有名称,而不是将redirect参数设置为to.fullPath您可以使用将其设置为to.name ,然后当用户登录时,您可以按名称重定向到路由。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM