登录的时候用到了重定向
面包屑导航用到了重定向 他是通过重定向导航来实现的
登录页面的重定向

// 监听路由的变化
$route: {
handler: function(route) {
// redirect后面的部分就会变成query
const query = route.query;
console.log(query)
if (query) {
// 将redirect提取出来同时将其他的参数放入到otherQuery
this.redirect = query.redirect
this.otherQuery = this.getOtherQuery(query)
}
},
// immediate :在create的时候就会进行调用
immediate: true
}
getOtherQuery:
getOtherQuery(query) {
return Object.keys(query).reduce((acc, cur) => {
if (cur !== 'redirect') {
acc[cur] = query[cur]
}
return acc
}, {})
}
这样的话就分成了两部分,redirect 和 otherQuery
这样就定义好了
在哪里使用呢
handleLogin:
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
// 登录成功:跳转链接 优先跳转redirect路径
// redirect路径不存在的话,直接跳到/(dashborad)同时将otherQuery作为query传入进来
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
.catch(() => {
this.loading = false
})
} else {
console.log('error submit!!')
return false
}
})
},
重定向组件是如何实现的
redirect是个动态路由
<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>
可以看到是通过render函数进行渲染的
将query拿出来 然后将path从params拿出来
redirect是个动态路由 动态路由的配置方法:
path: '/redirect/:path*'
表示匹配零个或多个路由,比如路由为 /redirect 时,仍然能匹配到 redirect 组件。如果将路由改为:
path: '/redirect/:path'
此时路由 /redirect 将只能匹配到 Layout 组件,而无法匹配到 redirect 组件
如果*去掉,那么*只能匹配/之前的路径![]()
只能匹配到/book这里
我们在浏览器地址栏输入redirect/book 他首先会重定向到/book然后通过book的重定向再到/book/create
但是如果不加*的话就只能到/create了
如果加了*的话就代表不管有多少路由都能被匹配到
版权声明:本文为xiaozhazhazhazha原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。