Vue converts links into QR codes

1. Install qrcode

cnpm install --save qrcodejs2

2. Import into the project

import QRCode from 'qrcodejs2'

3. Use in the page

<el-dialog :title="查看二维码" :visible.sync="addDialogVisible" @close="closeDialog">
<div id="qrcode" ref="qrcode"></div>
</el-dialog>
<script>
import QRCode from 'qrcodejs2'
export default{
    data(){
      return {
        addDialogVisible: false,
        url: 'https://first-1300696665.cos.ap- 
              nanjing.myqcloud.com/commons/a3cdd0a4680f4e54856ad0eb247df3cf.jpg'
      }
    }
    methods:{
       openDialog() {
          this.addDialogVisible = true
          this.$nextTick(() => {
             this.qrcodeGenerate()
          })
       },
       qrcode() {
          let qrcode = new QRCode('qrcode', {
             width: 200, // 设置宽度,单位像素
             height: 200, // 设置高度,单位像素
             text: this.url // 设置二维码内容或跳转地址
          })
       },
       // 关闭对话框时一定要清空二维码,否则下次打开对话框就会多一个
       closeDialog() {
       document.getElementById('qrcode').innerHTML = "";  
     }
    }
}
</script>

Precautions:

   If an error is reported: Cannot read property 'appendChild' of null

   Reason analysis: div has not been generated yet, you have obtained div

   Workaround: Use the this.$nextTick() method to execute a delayed callback after the next DOM update cycle ends.

 

Guess you like

Origin blog.csdn.net/m0_59735348/article/details/127011821