WechatLoginDialog.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. import QrcodeVue from "qrcode.vue";
  14. export default {
  15. name: "WechatLoginDialog",
  16. components: { QrcodeVue },
  17. props: {
  18. visible: Boolean,
  19. username: String,
  20. redirect: String
  21. },
  22. data() {
  23. return {
  24. qrUrl: "", // 微信扫码登录URL(用来生成二维码内容)
  25. ticket: "",
  26. status: "waiting",
  27. timer: null,
  28. errorShown: false
  29. };
  30. },
  31. watch: {
  32. visible(newVal) {
  33. if (newVal && this.username) this.open(this.username);
  34. }
  35. },
  36. methods: {
  37. open(username) {
  38. getWechatQrCode({ username }).then(res => {
  39. this.ticket = res.data.state;
  40. const win = window.open(res.data.url); // 新开窗口扫码
  41. this.startPolling(win); // 传入窗口对象
  42. });
  43. },
  44. startPolling(win) {
  45. this.timer = setInterval(() => {
  46. checkWechatScan(this.ticket)
  47. .then(res => {
  48. if (res.code === 200 && res.data) {
  49. this.status = "success";
  50. clearInterval(this.timer);
  51. console.log("扫码成功,准备 emit 事件", res.data);
  52. this.$emit("update:visible", false);
  53. this.$emit("loginSuccess", res.data);
  54. if (win && !win.closed) {
  55. win.close(); // 扫码完成后自动关闭窗口
  56. }
  57. }
  58. })
  59. .catch(err => {
  60. clearInterval(this.timer);
  61. this.$emit("update:visible", false);
  62. if (!this.errorShown) {
  63. this.errorShown = true;
  64. this.$message.error(err.response?.data?.msg );
  65. }
  66. if (win && !win.closed) {
  67. win.close(); // 异常也关闭窗口
  68. }
  69. });
  70. }, 800);
  71. }
  72. },
  73. beforeDestroy() {
  74. if (this.timer) clearInterval(this.timer);
  75. }
  76. };
  77. </script>