vue

vue自动生成二维码并下载本地

2022-01-19  本文已影响0人  吃肉肉不吃肉肉

vue生成二维码图片,这里使用的是qrcode.js 这个插件

1、下载插件

npm install --save qrcodejs2

2、组件内使用

<template>
 <el-button type="text" @click="getDownload(row)">下载</el-button>
 <!--二维码-->
  <div id="qrcode" class="qrcode" />  // 设置display: none;可隐藏二维码,只显示下载按钮
</template>
import QRCode from 'qrcodejs2'; ///引用
methods: {
  // 获取二维码
    creatQrCode(id) {
      const qrcode = new QRCode('qrcode', {
        text: 'http://xxx?id=' + id, // 需要转换为二维码的内容
        width: 240,
        height: 240,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      return qrcode
    },
// 下载二维码
    getDownload(row) {
      this.creatQrCode(row.id) // 生成二维码
      // 先找到canvas节点下的二维码图片
      const myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas')
      const img = document.getElementById('qrcode').getElementsByTagName('img')
      // 创建一个a节点
      const a = document.createElement('a')
      // 设置a的href属性将canvas变成png格式
      const imgURL = myCanvas[0].toDataURL('image/jpg')
      const ua = navigator.userAgent
      if (ua.indexOf('Trident') !== -1 && ua.indexOf('Windows') !== -1) { // IE内核 并且  windows系统 情况下 才执行;
        var bstr = atob(imgURL.split(',')[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, '下载' + '.' + 'png')
      } else if (ua.indexOf('Firefox') > -1) { // 火狐兼容下载
        const blob = this.base64ToBlob(imgURL) // new Blob([content]);
        a.download = ' '// 下载图片名称,如果填内容识别不到,下载为未知文件,所以我这里就不填为空
        a.href = URL.createObjectURL(blob)
        a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))// 兼容火狐
      } else { // 谷歌兼容下载
        img.src = myCanvas[0].toDataURL('image/jpg')
        a.href = img.src
        // 设置下载文件的名字
        a.download = row.title
        // 点击
        a.click()
      }
    }
}
<style lang="scss">
.qrcode{
    display: none; // 可隐藏二维码
    img {
        width: 260x;
        height: 260px;
        background-color: #fff; //设置白色背景色
        padding: 6px; // 利用padding的特性,挤出白边
        box-sizing: border-box;
    }
}
</style>
上一篇下一篇

猜你喜欢

热点阅读