Vue使用QRCode2插件,生成二维码及错误提示Cannot read property ‘appendChild‘ of undefined

组件附上

<template>
<a-col :span="24">
  <a-form-item label="二维码" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <div class="qrcode" ref="qrCodeUrl"></div>
  </a-form-item>
  </a-col>
</template>

<script>
  import Vue from 'vue'
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JUpload from '@/components/jeecg/JUpload'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
   import QRCode from 'qrcodejs2'

  export default {
    name: "QRCodeView",
    data() {
      return {
        link: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      }
    },
    props: {
      text: {
       type: String,
       required: true,
        default: '',
      },
    },
    watch: {
      text: {
        immediate: true,
        handler() {
          
          if (this.text != '' && this.text != null) {
            this.link = this.text
          } else {
           this.text='https://www.baidu.com/'
         }
        },
      },
    },
    mounted: function () {       
        this.creatQrCode();
    },
    methods: {
      
      creatQrCode() {
        this.$nextTick(function () {
          setTimeout(() => {
          var qrcode = new QRCode(this.$refs.qrCodeUrl, {
              text: this.link,//this.link, // 需要转换为二维码的内容
              width: 100,
              height: 100,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H
          })
         }, 500);
     })
    },
    }
  }
</script>

引用即可

<QRCodeView :text="link"></QRCodeView>

至于为什么会报错
是因为dom节点还没渲染好,调用方法时加上

 this.$nextTick(function () {}

即可,
当然,最好加一个延时函数

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值