vue实现生成二维码完整demo(qrcode方式)

在Vue项目中使用qrcodejs2库生成二维码时遇到报错,错误提示为无法读取未定义的属性appendChild。通过在创建二维码的函数中添加setTimeout延迟执行,可以确保在DOM渲染完成后再生成二维码,从而解决问题。在延迟执行的函数中,成功创建并显示了二维码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue用qrcode生成二维码

1.安装依赖

npm i qrcodejs2 --save

2.代码实现

<template>
  <div>
    <div class="qrcode" ref="qrCodeUrl"></div>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  export default {
    data() {
      return {};
    },
    methods: {
      creatQrCode() {
        var that = this
        var qrcode = new QRCode(that.$refs.qrCodeUrl, {
          text: "leon", // 需要转换为二维码的内容
          width: 200,
          height: 200,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      },
    },
    mounted() {
      this.creatQrCode();
    },
  };
</script>

<style scoped="scoped" lang="scss">
  .qrcode {}
</style>

demo页面二维码显示正常,但在嵌入到业务页面中报错,控制台错误提示为:

TypeError: Cannot read properties of undefined (reading 'appendChild')

意思是:未捕获的类型错误: 无法读取未定义的属性(读取‘ appendchild’)

也就是说,你在使用appendChild时的父元素上没有这个属性,所以没法使用。

此时通过增加setTimeout的方式进行处理后,可以正常显示:

<template>
  <div>
    <div class="qrcode" ref="qrCodeUrl"></div>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  export default {
    data() {
      return {};
    },
    methods: {
      creatQrCode() {
        var that = this
        setTimeout(() => {
          var qrcode = new QRCode(that.$refs.qrCodeUrl, {
            text: "leon", // 需要转换为二维码的内容
             width: 200,
             height: 200,              colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
          })
        }, 100)
      },
    },
    mounted() {
      this.creatQrCode();
    },
  };
</script>

<style scoped="scoped" lang="scss">
  .qrcode {}
</style>

结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值