天天看点

vue 生成二维码并下载

vue 项目中需要实现生成二维码,并且下载下来。

引入 qrcode :

import QRCode from "qrcodejs2"      

生成二维码:

createQRCode () {
      document.getElementById("qrcode").innerHTML = "" 
      let qrcode = new QRCode(this.$refs['qrCodeDiv'], {
        text: 'https://www.baidu.com/',
        width: 188, //生成的二维码的宽度
        height: 188, //生成的二维码的高度
        colorDark: "#666666", // 生成的二维码的深色部分
        colorLight: "#ffffff", //生成二维码的浅色部分
        correctLevel: QRCode.CorrectLevel.H
      })
      this.downloadQRCode()
    }
      

下载二维码:

downloadQRCode () {
      let qrcode = document.getElementById('qrcode');
      let img = qrcode.getElementsByTagName('img')[0];
      img.onload = function () {
        this.imgUrl = img.getAttribute("src");
        let link = document.createElement("a");
        link.setAttribute("href", this.imgUrl);
        link.setAttribute("download", '123.png')
        link.click();
      }
    }
      
<template>
  <div class="link-container">   
    <el-button @click="createQRCode">下载二维码</el-button>
    <div id="qrcode" ref="qrCodeDiv"></div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2"
export default {
  name: 'Link',
  components: {
    QRCode
  },
  data () {
    return {      
    }
  },
  props: {
  },
  watch: {},
  created () {    
  },
  methods: {
    createQRCode () {
      document.getElementById("qrcode").innerHTML = "" 
      let qrcode = new QRCode(this.$refs['qrCodeDiv'], {
        text: 'https://www.baidu.com/',
        width: 188, //生成的二维码的宽度
        height: 188, //生成的二维码的高度
        colorDark: "#666666", // 生成的二维码的深色部分
        colorLight: "#ffffff", //生成二维码的浅色部分
        correctLevel: QRCode.CorrectLevel.H
      })
      this.downloadQRCode()
    },
    downloadQRCode () {
      let qrcode = document.getElementById('qrcode');
      let img = qrcode.getElementsByTagName('img')[0];
      img.onload = function () {
        this.imgUrl = img.getAttribute("src");
        let link = document.createElement("a");
        link.setAttribute("href", this.imgUrl);
        link.setAttribute("download", '123.png')
        link.click();
      }
    }
  }
}
</script>

<style lang='less'>
</style>