路由重定向原理解析

登录重定向

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拦截
登录组件实现细节

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

f(me)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值