扫码二维码是现在移动应用中一个非常重要的功能,微信小程序中,我们可以通过 wx.scanCode 这个函数,在小程序中加入扫码的功能。

wx.scanCode 定义

1
2
3
4
5
6
7
8
9
10
11
12
13
wx.scanCode({
success (res) {
console.log(res)
}
})

// 只允许从相机扫码
wx.scanCode({
onlyFromCamera: true,
success (res) {
console.log(res)
}
})

在示例中,我们实现一个简单的扫码功能。

wxml代码如下:

1
2
3
4
<view>  
<view bindtap="scan">点我扫一扫</view>
<view>{{show}}</view>
</view>

javascript代码如下:

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
27
28
29
30
31
32
33
const app = getApp()

Page({
data: {
show: ''
},
scan: function(e) {
var that = this
var show
wx.scanCode({
success: (res) => {
this.show = "结果:" + res.result + ", 二维码类型:" + res.scanType + ", 字符集:" + res.charSet + ", 路径:" + res.path;
that.setData({
show: this.show
})
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000
})
},
fail: (res) => {
wx.showToast({
title: '失败',
icon: 'success',
duration: 2000
})
},
complete: (res) => {
}
})
}
})