使用qrcode 前端生成二维码

  1. 安装依赖
bash 复制代码
npm install qrcode
  1. 在Vue中使用
bash 复制代码
<template>
  <div class="qr-code-generator">
    <input
      v-model="text"
      type="text"
      placeholder="请输入要生成二维码的内容"
      class="input-box"
    />
    <button @click="generateQRCode" class="generate-btn">生成二维码</button>
    <canvas ref="qrCanvas" class="qr-canvas"></canvas>
  </div>
</template>

<script>
import QRCode from "qrcode";

export default {
  name: "QRCodeGenerator",
  data() {
    return {
      text: "", 
    };
  },
  methods: {
    generateQRCode() {
      const canvas = this.$refs.qrCanvas;
      if (this.text.trim()) {
        QRCode.toCanvas(canvas, this.text, { errorCorrectionLevel: "H" }, (error) => {
          if (error) {
            console.error("二维码生成失败", error);
          }
        });
      } else {
        alert("请输入内容");
      }
    },
  },
  //下载图片
   downloadQRCode () {
	  const canvas = this.$refs.qrCanvas;
	  const url = canvas.toDataURL();
	  const link = document.createElement("a");
	  link.href = url;
	  link.download = "qrcode.png";
	  link.click();
	};
};
</script>

<style scoped>
.qr-code-generator {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.input-box {
  padding: 10px;
  width: 300px;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.generate-btn {
  padding: 10px 20px;
  border: none;
  background-color: #4caf50;
  color: white;
  cursor: pointer;
  border-radius: 5px;
}

.qr-canvas {
  margin-top: 20px;
}
</style>
  1. 拓展
  • 样式自定义
bash 复制代码
QRCode.toCanvas(canvas, this.text, {
  width: 300,
  color: {
    dark: "#000", // 二维码颜色
    light: "#fff", // 背景颜色
  },
});
  • 支持多种生成方式
    通过 v-if 或 v-show 切换不同生成方式,比如直接展示在 标签中:
bash 复制代码
QRCode.toDataURL("your text").then((url) => {
  this.imageSrc = url;
});
相关推荐
sanggou24 分钟前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友28 分钟前
C++与Qt图形开发
开发语言·c++·算法
!win !32 分钟前
前端跨标签页通信方案(下)
前端·javascript
f***453243 分钟前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
编码追梦人1 小时前
从 “手忙脚乱“ 到 “行云流水“:华为云 DevUI 与 MateChat 如何让前端开发飞起来
前端·华为云
yue0081 小时前
C# 更改窗体样式
开发语言·c#
普通网友1 小时前
C++中的适配器模式
开发语言·c++·算法
风闲12171 小时前
Qt源码编译记录
开发语言·qt
普通网友1 小时前
C++中的委托构造函数
开发语言·c++·算法
用户47949283569152 小时前
TypeScript 简史:它是怎么拯救我的烂代码的
javascript·typescript