路由重定向原理解析

登录重定向

login.vue 中对 $route 进行监听:

watch: {
    
    
  $route: {
    
    
    handler: function(route) {
    
    
      const query = route.query
      if (query) {
    
    
        this.redirect = query.redirect
        this.otherQuery = this.getOtherQuery(query)
      }
    },
    immediate: true //在初始化的时候就会进行调用
  }
}

this.getOtherQuery(query) 的用途是获取除 redirect 外的其他查询条件,登录成功后:

this.$store.dispatch('user/login', this.loginForm)
.then(() => {
    
    
  this.$router.push({
    
     path: this.redirect || '/', query: this.otherQuery })
  this.loading = false
})
.catch(() => {
    
    
  this.loading = false
})

完成重定向的代码为:

this.$router.push({
    
     path: this.redirect || '/', query: this.otherQuery })

重定向组件

vue-element-admin 提供了专门的重定向组件,源码如下:

<script>
export default {
    
    
  created() {
    
    
    const {
    
     params, query } = this.$route
    const {
    
     path } = params
    this.$router.replace({
    
     path: '/' + path, query })
  },
  render: function(h) {
    
    
    return h() // avoid warning message
  }
}
</script>

重定向组件配置了动态路由:

{
    
    
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
    
    
        path: '/redirect/:path*',
        component: () => import('@/views/redirect/index')
      }
    ]
}

这里有一个细节:

path: '/redirect/:path*'

表示匹配零个或多个路由,比如路由为 /redirect 时,仍然能匹配到 redirect 组件。如果将路由改为:

path: '/redirect/:path'

此时路由 /redirect 将只能匹配到 Layout 组件,而无法匹配到 redirect 组件

Vue admin
登陆流程
界面精简及路由处理(实现了权限控制)
路由和权限校验原理
侧边栏
重定向
面包屑导航
requst库 axios拦截
登录组件实现细节

猜你喜欢

转载自blog.csdn.net/qq_52151772/article/details/111304461