<template>
  <div>
    <input type="text" value="666" v-model="text" placeholder="请输入要生成二维码的内容">
    <button @click="showQRCodeDialog">生成二维码</button>
    <van-dialog
      v-model:show="dialogVisible"
      title="二维码"
      width="80%"
      :before-close="handleClose"
    >
    <div class="qrcode-container">
    <div id="qrcode"></div>
  </div>
    </van-dialog>
  </div>
</template>

<script setup>
import QRCode from 'qrcodejs2-fix';
import { ref } from 'vue';

const text = ref('');
const dialogVisible = ref(false);

const generateQRCode = () => {
  const qrcodeContainer = document.getElementById('qrcode');
  console.log('qrcodeContainer:', qrcodeContainer);
  if (!qrcodeContainer) {
    console.error('DOM element for QR code is not found.');
    return;
  }
  qrcodeContainer.innerHTML = ''; // 清空之前的二维码
  const qrCodeInstance = new QRCode(qrcodeContainer, {
    text: text.value,
    width: 200,
    height: 200
  });
};

const showQRCodeDialog = () => {
  dialogVisible.value = true; // 显示对话框
  generateQRCode(); // 生成二维码
};

const handleClose = () => {
  dialogVisible.value = false; // 关闭对话框时清空二维码
};

</script>

<style>
.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 如果需要垂直居中，可以设置容器高度为100% */
}
</style>
