使用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;
});
相关推荐
谎言西西里1 小时前
JS 高手必会:手写 new 与 instanceof
javascript
雪碧聊技术2 小时前
前端项目代码发生改变,如何重新部署到linux服务器?
前端·vue3·centos7·代码更新,重新部署
diegoXie2 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条2 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle2 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
wordbaby2 小时前
Expo 进阶指南:赋予 TanStack Query “原生感知力” —— 深度解析 AppState 与 NetInfo
前端·react native
Moment2 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
天问一2 小时前
使用 Vue Router 进行路由定制和调用的示例
前端·javascript·vue.js
失散133 小时前
Python——1 概述
开发语言·python
萧鼎3 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法