long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

vue QRCode生成二维码

Posted at 2019-08-19 笔记 前端 vue 

1、npm 安装qrcode

使用下面的命令安装qrcode
npm install --save qrcode
网上有好多的版本。比如说qrcodejs2等等。经过采坑之后才知道qscode是最可控的。qrcodejs2会生成一个位置让人凌乱的图片。

2、使用qrcode生成二维码图片

推荐去看官方的api,博客什么的各种牛马蛇神都有。

2.1 引入包
1
import QRCode from 'qrcode'
2.2 创建一个函数来生成二维码

也可以在vue的mounted中创建。
有两种方式生成二维码

  • 第一种 使用html中canvas标签
1
<canvas id="canvas" style="width:400px;height:400px;" class="qrcode" ref="canva" />

然后再js中生成二维码图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const canva = this.$refs.canva
QRCode.toCanvas(canva,`${this.qrCodeUrl}`,error => {
if (error) {
this.$message({
type: 'error',
message: '生成二维码失败'
})
} else {
this.$message({
type: 'success',
message: '生成二维码成功'
})
}
})
  • 第二种是直接产生二维码的urlData然后再进行处理显示。个人喜欢用可控的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 配置变量
const opts = {
errorCorrectionLevel: 'H',
type: 'image/jpeg',
renderOpts: {
quality: 0.3
}
}
QRCode.toDataURL(
'text',
opts,
function (err, url) {
if (error) {
this.$message({
type: 'error',
message: '生成二维码失败'
})
} else {
this.$message({
type: 'success',
message: '生成二维码成功'
})
this.qrImage = url;
}
}
)

es6写法

1
2
3
4
5
6
7
8
await QRCode.toDataURL(this.qrCodeUrl,opts)
.then(url => {
console.log(url)
alert('生成成功')
this.qrImage = url
}).catch(err => {
console.log(err)
})

3、生成的结果

Share 

 Previous post: javascript实现的小东西 Next post: Mybatis整合通用mapper 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo