WechatLoginDialog.vue 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <!--<template>-->
  2. <!-- <el-dialog title="微信扫码验证" :visible.sync="visible" width="300px">-->
  3. <!-- <div class="flex flex-col items-center justify-center">-->
  4. <!-- &lt;!&ndash; 直接用 qrcode-vue 生成二维码 &ndash;&gt;-->
  5. <!-- <qrcode-vue :value="qrUrl" :size="200" v-if="qrUrl" />-->
  6. <!-- <p v-if="status==='waiting'">请使用微信扫码确认</p>-->
  7. <!-- <p v-if="status==='success'">验证成功,正在跳转...</p>-->
  8. <!-- </div>-->
  9. <!-- </el-dialog>-->
  10. <!--</template>-->
  11. <script>
  12. import { getWechatQrCode, checkWechatScan } from "@/api/login";
  13. export default {
  14. name: "WechatLoginDialog",
  15. props: {
  16. visible: Boolean,
  17. username: String,
  18. redirect: String
  19. },
  20. data() {
  21. return {
  22. qrUrl: "", // 微信扫码登录URL(用来生成二维码内容)
  23. ticket: "",
  24. status: "waiting",
  25. timer: null,
  26. errorShown: false
  27. };
  28. },
  29. watch: {
  30. visible(newVal) {
  31. if (newVal && this.username) this.open(this.username);
  32. }
  33. },
  34. methods: {
  35. open(username) {
  36. getWechatQrCode({ username }).then(res => {
  37. this.ticket = res.data.state;
  38. const win = window.open(res.data.url); // 新开窗口扫码
  39. this.startPolling(win); // 传入窗口对象
  40. });
  41. },
  42. startPolling(win) {
  43. this.timer = setInterval(() => {
  44. checkWechatScan(this.ticket)
  45. .then(res => {
  46. if (res.code === 200 && res.data) {
  47. this.status = "success";
  48. clearInterval(this.timer);
  49. console.log("扫码成功,准备 emit 事件", res.data);
  50. this.$emit("update:visible", false);
  51. this.$emit("loginSuccess", res.data);
  52. if (win && !win.closed) {
  53. win.close(); // 扫码完成后自动关闭窗口
  54. }
  55. }
  56. })
  57. .catch(err => {
  58. clearInterval(this.timer);
  59. this.$emit("update:visible", false);
  60. if (!this.errorShown) {
  61. this.errorShown = true;
  62. this.$message.error(err.response?.data?.msg);
  63. }
  64. if (win && !win.closed) {
  65. win.close(); // 异常也关闭窗口
  66. }
  67. });
  68. }, 800);
  69. }
  70. },
  71. beforeDestroy() {
  72. if (this.timer) clearInterval(this.timer);
  73. }
  74. };
  75. </script>