Vue 生成二维码

灰太狼 2022-11-27 03:22 349阅读 0赞

https://www.cnblogs.com/TreeCTJ/p/12736833.html

https://blog.csdn.net/qq_25983579/article/details/103956798 Vue使用QRCode插件,生成二维码及错误提示Cannot read property ‘appendChild’ of null”

1.安装文件

  1. npm install --save qrcode2

2.引入文件

  1. import QRCode from 'qrcode2';

3.生成文件 (移动端宽高写 一半)

  1. // 生成二维码
  2. crateQrcode(text) {
  3. this.ewmmaskOff = true;
  4. this.$nextTick(() => {
  5. let qr = new QRCode(this.$refs.qrCodeUrl, {
  6. width: 400,
  7. height: 400, // 高度
  8. text: text, // 二维码内容
  9. colorDark: "#333",
  10. colorLight: "#fff", //二维码背景色
  11. correctLevel: QRCode.CorrectLevel.L,
  12. });
  13. });
  14. },

4.清空二维码

  1. document.getElementById("qrcode").innerHTML = "";

5.特别提醒

注意:一定要在div生成之后再生成二维码,否则就会出现Cannot read property ‘appendChild’ of null”的错误
this.$nextTick

其他

  1. 生成二维码使用 QRCode 生成二维码import QRCode from 'qrcode';
  2. // 使用 async 生成图片
  3. const options = {};
  4. const url = window.location.href;
  5. async url => {
  6. try {
  7. console.log(await QRCode.toDataURL(url, options))
  8. } catch (err) {
  9. console.error(err);
  10. }
  11. }
  12. await QRCode.toDataURL(url, options) 赋值给
  13. 图片 url 即可生成图片主要是使用 htmlToCanvas 生成 canvas 画布import html2canvas from 'html2canvas';
  14. html2canvas(document.body).then(function(canvas) {
  15. document.body.appendChild(canvas);
  16. });
  17. 但是不单单在此处就完了,由于是 canvas 的原因。
  18. 移动端生成出来的图片比较模糊。我们使用一个新的 canvas 方法多倍生成,
  19. 放入一倍容器里面,达到更加清晰的效果,通过超链接下载图片 下载文件简单实现,
  20. 更完整的实现方式之后更新const scaleSize = 2;
  21. const newCanvas = document.createElement("canvas");
  22. const target = document.querySelector('div');
  23. const width = parseInt(window.getComputedStyle(target).width);
  24. const height = parseInt(window.getComputedStyle(target).height);
  25. newCanvas.width = width * scaleSize;
  26. newCanvas.height = widthh * scaleSize;
  27. newCanvas.style.width = width + "px";
  28. newCanvas.style.height =width + "px";
  29. const context = newCanvas.getContext("2d");
  30. context.scale(scaleSize, scaleSize);
  31. html2canvas(document.querySelector('.demo'), { canvas: newCanvas }).then(function(canvas) {
  32. // 简单的通过超链接设置下载功能
  33. document.querySelector(".btn").setAttribute('href', canvas.toDataURL());
  34. }

发表评论

表情:
评论列表 (有 0 条评论,349人围观)

还没有评论,来说两句吧...

相关阅读