目标
从http://localhost:9528/#/a中退出之后,随后立即登录,还能再回到http://localhost:9528/#/a这里。
分析
- 登录成功之后,进入指定的目标页面(不要每次都进入主页)
- 用户退出,跳入登录页时,携带目标页面地址告诉登录页
登录成功后进入指定的页面
目标
自己来指定登陆成功之后,希望要进入的页面
思路
在访问login这个页面时,可以在地址栏中补充一个查询字符串来指定登陆成功之后要去到的页面。例如
# 访问登录页,并且告诉它,登录成功之后要进入 /abc
http://localhost:9528/#/login?return_url=/abc
落地代码
login/index.vue中的代码:
async doLogin() {
try {
// 在组件中调用带命名空间的action
// dispatch是异步的,需要加async await
await this.$store.dispatch('user/userLogin', this.loginForm)
// 登录成功,路由跳转
+ this.$router.push(this.$route.query.return_url || '/')
} catch (err) {
alert('用户登录,失败')
console.log('用户登录,失败', err)
}
},
退出系统时回传当前路径
目标
在退出时,跳回login时,回传当前的路径
代码
navbar.vue
logout() {
// 弹层询问,是否退出
this.$confirm('你确定要离开吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(async() => {
// 确认
// 删除信息
await this.$store.dispatch('user/userLogout')
// 去到登录页
// this.$router.push('/login?return_url=当前的路径')
// 跳转路由-回登陆
// 如何获取当前页面的地址 : this.$route.fullPath
// this.$route.path只有路径的信息
// this.$route.fullPath:路径+查询参数的信息
+ this.$router.push('/login?return_url=' + encodeURIComponent(this.$route.fullPath))
}).catch(() => {
})
}
注意:
- $route.path:只有路径的信息
- $route.fullPath:路径+查询参数的信息
- return_url: 这个名字是自己约定的,它要和login/index.vue中跳转代码保持一致。
- encodeURIComponent: 是js的内置API,用来对url进行编码