重定向

思考:你目前的项目中是如何实现重定向功能的?

登录重定向

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
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

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
})
1
2
3
4
5
6
7
8

完成重定向的代码为:

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

重定向组件

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>
1
2
3
4
5
6
7
8
9
10
11
12

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

{
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path*',
        component: () => import('@/views/redirect/index')
      }
    ]
}
1
2
3
4
5
6
7
8
9
10
11

这里有一个细节:

path: '/redirect/:path*'
1

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

path: '/redirect/:path'
1

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

上次更新: 11/17/2019, 11:38:59 AM