首页 > 解决方案 > 使用 VueJs 复制或下载生成的 QR (vue-qrcode) 代码

问题描述

我使用插件“vue-qrcode”为我的用户生成一个二维码,以链接到他们的公共个人资料,以便他们可以分享它,例如在他们的名片上。

现在的想法是让我的用户可以通过一个按钮下载二维码并通过另一个按钮将二维码复制到剪贴板,以便更容易地发送它,例如通过邮件(特别是智能手机用户)。

问题:我不知道如何下载或复制二维码。有人知道复制或下载二维码吗?目前我使用'vue-clipboard2'来复制链接等,但它似乎无法复制图像。

我使用以下代码在我们的网站上显示二维码:

<template>
  <qrcode-vue 
    style = "cursor: pointer;" 
    :value = "linkToProfile" 
    size = 160 
    level = "M"
    :background = "backgroundcolor_qrcode"
    :foreground = "color_qrcode"
  ></qrcode-vue>
</template>

<script>
  import Vue from 'vue'
  import QrcodeVue  from 'qrcode.vue'
  Vue.component('qrcode-vue', QrcodeVue )

  export default {
    data: () => ({
      linkToProfile: "http://www.example.com/johnDoe",
    })

</script>

谢谢 - 克里斯蒂安

标签: imagevue.jsdownloadcopyqr-code

解决方案


我想到了。解决方案如下所示:

模板区域:

  <qrcode-vue 
    id="qrblock"
    :value = "linkToSki" 
    size = 220
    level = "M"
    ref="qrcode"
  ></qrcode-vue>

功能区:

// -- FUNCTIONS AREA TO COPY / DOWNLOAD QR CODE - END ---
function selectText(element) {
    if (document.body.createTextRange) {
      const range = document.body.createTextRange();
      range.moveToElementText(element);
      range.select();
    } else if (window.getSelection) {
      const selection = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(element);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }

  function copyBlobToClipboardFirefox(href) {
    const img = document.createElement('img');
    img.src = href;
    const div = document.createElement('div');
    div.contentEditable = true;
    div.appendChild(img);
    document.body.appendChild(div);
    selectText(div);
    const done = document.execCommand('Copy');
    document.body.removeChild(div);
    return done;
  }

  function copyBlobToClipboard(blob) {
    // eslint-disable-next-line no-undef
    const clipboardItemInput = new ClipboardItem({
      'image/png' : blob
    });
    return navigator.clipboard
      .write([clipboardItemInput])
      .then(() => true)
      .catch(() => false);
  }

  function downloadLink(name, href) {
    const a = document.createElement('a');
    a.download = name;
    a.href = href;
    document.body.append();
    a.click();
    a.remove();
  }
  // -- FUNCTIONS AREA TO COPY / DOWNLOAD QR CODE - END ---

推荐阅读