vue3使用qrcode库生成二维码

629 阅读1分钟

<script setup>
// 引用
import QRcode from "qrcode";
import { ref, reactive, onMounted } from "vue";

const qrcodeCanvas = ref("");

const text = ref("");

const changeText = () => {
  if (text.value == "") {
    alert("文本内容不能为空");
  } else {
    createQR();
  }
};

const createQR = () => {
  QRcode.toCanvas(
    qrcodeCanvas.value,
    text.value, //输入url则跳转url,否则显示字符串
    {
      width: 200, //自定义宽度
      color: {
        dark: "#000000", //自定义码的颜色 只支持16进制
        light: "#ffffff", //自定义背景颜色 只支持16进制
      },
    }
  );
};
</script>
<template>
  <div class="test">
    <input type="text" placeholder="输入链接或文本" v-model="text" /><button
      @click="changeText()"
    >
      生成二维码
    </button>

    <div class="qrcode">
      <!-- 二维码容器-->
      <canvas ref="qrcodeCanvas"> </canvas>
    </div>
  </div>
</template>


<style  scoped>
canvas {
  border: 1px solid;
}
</style>