vue3 使用 qrcode.vue 生成二维码

需求

  1. 前端根据后台返回链接生成二维码
  2. 复制链接
  3. 下载生成的二维码图片

前言

vue2项目中有 qrcode qrcodejs qrcodejs2 等插件可以很好的实现,but vue3 项目中第一次操作 发现这几个插件都不支持 于是找了好久找到支持3的插件 戳我查看qrcode.vue ok 上代码:

安装

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>
复制代码

使用

//main.ts中注册全局组件
import QrCode from './components/QrCode.vue'
const app = createApp(App)
app.component('qr-code',QrCode)
复制代码
//组件中使用
<qr-code :value="links" :size="150" id="canvasDom"></qr-code>
复制代码

下载链接

下载链接需要将要下载的内容放置到一个input中 可以设置 position: absolute;z-index: -1;脱离文档流并隐藏

const copyLink = ():void => {
    state.copyUrl = state.links
    setTimeout(() => {
        const copyDom = document.getElementById('copy-input') as HTMLInputElement;
        copyDom.select()
        document.execCommand("Copy"); //复制
        ElMessage({
            type:'success',
            message:'复制成功!'
        })
    })
}
复制代码

下载qrcode生成的二维码

const downLoadQRcode = ():void => {
    const canvas = document.getElementById('canvasDom') as HTMLCanvasElement
    const url = canvas.toDataURL("image/png") // 通过 toDataURL 返回一个包含图片展示的 data URI 
    const aDom = document.createElement("a")
    aDom.download = state.linksName// 设置下载的文件名
    aDom.href = url
    document.body.appendChild(aDom)
    aDom.click()
    aDom.remove()
}
复制代码

提出问题

vue3 中通过 ref 获取canvas 元素 使用 canvas.toDataURL() 报错 Uncaught TypeError: canvas.toDataURL is not a function

通过原生jsdocument.getElementById的方式获取dom可以使用?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享