在 Vue 2 后台系统中实现短轮询的用户扫码登录功能,需要在前端组件中设置一个定时器,定时向后端发送请求以检查扫码状态。以下是一个基本的实现示例:
<template>
<div>
<h2>扫码登录</h2>
<p>{{ loginStatusText }}</p>
</div>
</template>
<script>
export default {
data() {
return {
loginStatusText: '请扫描二维码进行登录...',
checkInterval: null, // 用于存储 setInterval 的返回值
};
},
created() {
this.startCheckingLoginStatus();
},
beforeDestroy() {
if (this.checkInterval) {
clearInterval(this.checkInterval); // 清除定时器
}
},
methods: {
checkLoginStatus() {
this.$http.get('/api/check-login-status') // 使用 Vue 2 的 axios 实例
.then(response => {
const data = response.data;
if (data.status === 'success') {
this.loginStatusText = '登录成功!';
this.stopCheckingLoginStatus();
// 执行登录成功的后续操作,如跳转到后台系统首页
} else if (data.status === 'pending') {
// 保持当前状态
} else {
this.loginStatusText = '扫码登录失败,请重试。';
this.stopCheckingLoginStatus();
}
})
.catch(error => {
console.error('检查登录状态时发生错误:', error);
this.loginStatusText = '检查扫码状态出错,请重试。';
this.stopCheckingLoginStatus();
});
},
startCheckingLoginStatus() {
this.checkInterval = setInterval(this.checkLoginStatus, 5000); // 每5秒检查一次
},
stopCheckingLoginStatus() {
clearInterval(this.checkInterval);
this.checkInterval = null;
},
},
};
</script>
```### 服务器端伪代码服务器端需要实现 `/api/check-login-status` 接口,返回用户扫码的状态:```json
// 如果扫码成功{ "status": "success"}
// 如果扫码未完成{ "status": "pending"}
// 如果扫码超时或出错{ "status": "error"}
```在这个示例中,我们使用了 Vue 2 的 `data` 来存储登录状态文本和定时器的引用。
在组件创建时(`created` 钩子),我们开始检查登录状态。
组件销毁前(`beforeDestroy` 钩子),我们清除定时器以避免内存泄漏。
`checkLoginStatus` 方法通过 `axios` 发起 GET 请求到服务器检查扫码状态,并根据返回的状态更新前端的显示文本,并在成功或失败时停止轮询。
请根据你的实际项目需求调整 API 路径、状态管理和后续的业务逻辑处理。