vue项目实现生成一个简单二维码

vue项目中实现的 一个简单的二维码生成例子

首先安装一下插件

npm install qrcodejs2 --save

然后尝试走通下面的业务

<template>
  <div class="qrcode">
    <h1>生成二维码</h1>
    <label for="text">请输入要转换为二维码的内容:</label>
    <input type="text" id="text" v-model="text" @keyup.enter="generateQRCode" />
    <button @click="generateQRCode">生成</button>
    <button @click="returnClear">清空</button>
    <div ref="qrcode" style="margin: 0 auto" id="divdemo"></div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
export default {
  name: "QRCodeGenerator",
  data() {
    return {
      text: "",
      qrcode: null,
    };
  },
  methods: {
    generateQRCode() {
      if (this.qrcode != null) {
        this.qrcode.clear(); // 清除原来的二维码
        // 上面的清除方式无效,因此使用下面的强制清除
        let divdeom = document.getElementById("divdemo");
        divdeom.innerHTML = "";
      }
      this.qrcode = new QRCode(this.$refs.qrcode, {
        width: 256,
        height: 256,
        text: this.text,
      });
    },
    // 清除二维码以及输入框中的内容
    returnClear() {
      let divdeom = document.getElementById("divdemo");
      divdeom.innerHTML = "";
      this.text = "";
    },
  },
};
</script>

<style>
.qrcode input[type="text"] {
  width: 20%;
  padding: 10px;
  font-size: 18px;
  margin-bottom: 20px;
}

.qrcode button {
  background-color: #4caf50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.qrcode button:hover {
  background-color: #45a049;
}

.qrcode div {
  margin-top: 20px;
}

button {
  margin: 10px;
}
</style>

最后,如果上面的流程都能走通,那么,就可以按照自己项目的时机需求去再做开发了,至少生成二维码的功能已经实现了。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>