demand

  1. The front end generates the QR code according to the back link
  2. Copy the link
  3. Download the generated QR code image

preface

Qrcode, QrcodeJS, qrcodejs2 and other plug-ins in vue2 project can be well implemented, but the first operation of vue3 project found that these plug-ins do not support 3, so I searched for a long time to find a plug-in that supports 3.

The installation

yarn add qrcode.vue

qrcode.vue

<template>
  <qrcode-vue :value="value" :size="size" level="H" />
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import QrcodeVue from 'qrcode.vue'
export default defineComponent({
  props: {value: {type:String.require:true
    },
    size: {type:Number.default:100}},components:{
    QrcodeVue
  },
  setup(props) {
    const state = reactive({
      value:props.value,
      size:props.size
    })
    return {
      ...toRefs(state),
    }
  },
})
</script>
Copy the code

use

// Register global components in main.ts
import QrCode from './components/QrCode.vue'
const app = createApp(App)
app.component('qr-code',QrCode)
Copy the code
// used in the component
<qr-code :value="links" :size="150" id="canvasDom"></qr-code>
Copy the code

Download link

The download link requires that the content to be downloaded be placed in an input. z-index: -1; Leave the document flow and hide

const copyLink = ():void= > {
    state.copyUrl = state.links
    setTimeout(() = > {
        const copyDom = document.getElementById('copy-input') as HTMLInputElement;
        copyDom.select()
        document.execCommand("Copy"); / / copy
        ElMessage({
            type:'success'.message:'Copy succeeded! '})})}Copy the code

Download the qrcode generated by qrcode

const downLoadQRcode = ():void= > {
    const canvas = document.getElementById('canvasDom') as HTMLCanvasElement
    const url = canvas.toDataURL("image/png") // Return a data URI containing the image presentation via toDataURL
    const aDom = document.createElement("a")
    aDom.download = state.linksName// Set the file name for the download
    aDom.href = url
    document.body.appendChild(aDom)
    aDom.click()
    aDom.remove()
}
Copy the code

Ask questions

Uncaught TypeError: Canvas. toDataURL is not a function

Through native jsdocument. GetElementById for dom can be used?