qrcode根据本地数据生成二维码第一次显示跨页面后显示异常

最近写二维码的时候,突然想起之前项目遇到过的一个问题,网上也没有这方面解答,想到大家今后可能也会遇到这类问题,在此记录下来,希望对你们有所帮助,大佬们不喜勿喷,qrcode配合画布canvas本地生成二维码的时候第一次能够正常显示,最下方会贴出代码

 

 

 

 

跨页面后显示异常

 

 

刚开始是有些头疼的,因为控制台一切正常,没有抛出错误,然后去看qrcode的参数属性也没有问题,我是多个页面需要生成多个二维码,封装了qrcode组件

 

 

 F12逐步排查看html结构,生成多个二维码之后并没有销毁

 

 

 所以第一想到的是可能是覆盖问题,我也不知道为什么关闭窗口后并没有销毁,那么就手动remove()销毁它吧,结果还是悲剧的,依旧没有效果,通过打印结果可以得知二维码是正常生成了的只是没有被渲染上去

 

 

难道是跨页面的时候当前页面的id和其他页面的id重复导致qrcode生成二维码成功了但是画布无法正常显示吗,那么只需要每个引用了qrcode组件的页面都传一个唯一的值过来做id就行了,抱着试一试的态度我再次打开了vscode,将父组件的name传了过来

父组件

子组件id

props

 

 

 

 之后再获取到nameOn生成二维码,还挺好用

<template>
  <div>
         <!-- 单据二维码 --> < el-table-column :label ="$t('receipt.orderQRCode')" header-align ="center" align ="center" min-width ="150" > < template slot-scope ="scope" > < el-button type ="primary" @click ="createORCode(scope.row.receiptOrder)" > {{$t('receipt.generateQRcode')}} </ el-button > </ template > </ el-table-column >
            <!-- 生成二维码弹框 -->
          <q-r-code-dialog v-if="codeDialogVisible"
                       :orderNumber="orderNumber"
                       :nameOn="this.$options.name"
                       ref="codeDialog"
                       @confirm="createORCode">
          </q-r-code-dialog>
    </div>
</template>
     /*  *
* 生成二维码
*/ createORCode (orderNumber) { this .codeDialogVisible = true this .orderNumber = orderNumber this .$nextTick(() => { this .$refs.codeDialog.init()
})
},

qrcode公共组件

<template>
  <!-- 二维码 -->
  <el- dialog
width
="400px" :title ="$t('receipt.viewQRCode')" :close -on-click-modal="false" :visible.sync ="visible" @closed ="visible = false" :append -to-body="true" > <el-container style="margin-left: 5px"> <el-header style="height: 15px"> {{ $t( "receipt.documentNo") + ":" + orderNumber }} </el-header> <el-main> <canvas :id="nameOn" class="canvas"></canvas> </el-main> </el-container> </el-dialog> </template> <script> import QRCode from 'qrcode' export default {
name:
'QRCode' ,
props: {
orderNumber: {
type: String,
default : '' },
nameOn: {
type: String,
default : '' }
},
data () {
return {
visible:
false }
},
methods: {
// 初始化 init () { this .visible = true this .$nextTick(() => {
console.log(
this .orderNumber, 'orderNumber' ) // console.log(this.nameOn, 'name') if ( this .orderNumber) { // this.viewImgVisible = true // 生成二维码 let opts = {
errorCorrectionLevel:
'H' ,
type:
'image/jpeg' ,
rendererOpts: {
quality:
0.3 }
}
console.log(opts,
'opts' )
let canvasEle
= document.querySelector(`#${ this .nameOn}`)
QRCode.toDataURL(canvasEle,
this .orderNumber, opts, function (err) { if (err) throw err
})
}
})
}
}
}
</script> <style scoped> .canvas {
margin
-left: 10% ;
width:
80% ! important;
height:
80% ! important;
}
</style>

 

标签: Javascript

添加新评论