1.登錄頁面的重定向分析
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 })
2.重定向組件
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 組件
