携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情
1.常用的实现用户退出
分析
弹框提示用户是否确定退出
- 如果点击确认
1. 首先看看接口文档有没有退出接口,有的话就调用(注意并不是所有的项目,都有退出接口)
2. 退出接口成功调用之后清空本地用户信息(token、userInfo)
3. 如果需要携带必要参数跳回到登录页面准备重新登录操作
- 如果点击取消 不做任何操作
思路
编辑
步骤
1.在 action里面封装一个 用来退出的代码
userLogout(context){
context.commit('removeUserInfo')
context.commit('removeToken')
}
2.调用action 当用户点击退出时,显示确认对话框
logout() {
// 弹层询问,是否退出
this.$confirm('你确定要离开吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(async() => {
await this.$store.dispatch('user/logout')
this.$router.push(`/login`)
}).catch(() => {
// 用户取消退出
})
}
3.补充action
store/modules/user.js
logout(context) {
// 删除token
context.commit('reomveToken')
// 删除userInfo
context.commit('reomveUserInfo')
}
查看效果
在vue调试工具中,检查本地用户信息,检查是否已经清空了
小结
退出之前要询问,confirm对话框
退出之前要清空数据,由于这个数据是保存在vuex中的,使用action来删除
2.退出再进入能回到原来的页面 - 分析
分析
从http://localhost:9528/#/a中退出之后,随后立即登录,还能再回到http://localhost:9528/#/a这里
- 登录成功之后,进入指定的目标页面(不要每次都进入主页)
- 用户退出,跳入登录页时,携带目标页面地址告诉登录页
1.登录成功后进入指定的页面
在访问login这个页面时,可以在地址栏中补充一个查询字符串来指定登陆成功之后要去到的页面。
例如
访问登录页,并且告诉它,登录成功之后要进入 /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)
}
},
2.退出系统时回传当前路径
在退出时,跳回login时,回传当前的路径
实现代码
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进行编码