微信小程序 camera组件实现自定义界面的扫码功能

时间:2024-10-03 15:26:11

目录

使用到的功能点:

代码实现:


效果图:


想要实现自定义界面的扫码,这里用到了微信小程序的媒体组件

⚠️:同一页面只能插入一个 camera 组件

使用到的功能点:

1. camera

  • mode=scanCode // 扫码模式
  • binderror  //用户不允许使用摄像头时触发
  • bindscancode // 在扫码识别成功时触发,仅在 mode="scanCode" 时生效

2.<cover-image> 也可使用image替代  // 覆盖camera原有的样式

3.跳转URL携带参数字符长度过长,需要encodeURIComponent编码URI

 

cover-view 与 cover-image

为了解决原生组件层级最高的限制。小程序专门提供了 cover-view 和 cover-image 组件,可以覆盖在部分原生组件上面。这两个组件也是原生组件,但是使用限制与其他原生组件有所不同。

代码实现:

  1. // . 扫码页
  2. <view>
  3. <camera class="scan-area" @scancode="onScancode" @error="onError" mode="scanCode" device-position="back" flash="off">
  4. // <cover-image src="/static/image/"></cover-image>
  5. <image src="/static/image/"></image>
  6. </camera>
  7. <text>将二维码/条码放入框内,即可自动扫描</text>
  8. <view class="btn">
  9. <view class="photo">
  10. <img @click="onPhoto" src="/static/image/" alt="" />
  11. <text>相册</text>
  12. </view>
  13. </view>
  14. </view>
  15. <script>
  16. import * as utils from "@/utils/index";
  17. export default({
  18. data(){
  19. return{
  20. hasScan: false// false 还未跳转,true 已跳转一次
  21. }
  22. },
  23. onHide() { // 生命周期回调—监听页面隐藏
  24. this.hasScan = false
  25. },
  26. onUnload() { //生命周期回调—监听页面卸载
  27. this.hasScan = false
  28. },
  29. methods: {
  30. /**
  31. * 扫码识别成功时触发,跳转至扫描详情页
  32. * 防止扫码成功后页面多次跳转这里需要双重校验:
  33. * 第一层校验:延迟跳转
  34. * 第二层校验:使用变量控制hasScan是否跳转
  35. * */
  36. onScancode: utils.throttle(function (e) {
  37. let bid = e.detail.result;
  38. if (!this.hasScan) {
  39. wx.navigateTo({
  40. url: `/sub_scan/scan_details/index?bid=` + encodeURIComponent(JSON.stringify(bid)),
  41. success: function(){
  42. this.hasScan = true
  43. }
  44. });
  45. }
  46. }, 1000),
  47. }
  48. })
  49. </script>

  方法:

  1. //
  2. /**
  3. * 防止小程序多次点击跳转
  4. * @param {*} obj
  5. * @returns
  6. */
  7. export function throttle(fn, gapTime) {
  8. if (gapTime == null || gapTime == undefined) {
  9. gapTime = 1500
  10. }
  11. let _lastTime = null
  12. // 返回新的函数
  13. return function () {
  14. let _nowTime = + new Date()
  15. if (_nowTime - _lastTime > gapTime || !_lastTime) {
  16. fn.apply(this, arguments) //将this和参数传给原函数
  17. _lastTime = _nowTime
  18. }
  19. }
  20. }

scan_detail.vue 接收扫码页面的参数

  1. // scan_detail.vue ,扫描详情页
  2. onLoad(option) {
  3. this.BID = JSON.parse(decodeURIComponent(option.bid)); // 拿到参数bid
  4. if (!utils.isNullOrEmpty(this.BID) && this.BID.indexOf('did:bid') > -1) {
  5. // 当有bid的时候,loading先暂时加载着,直到接口内容返回后,才需要将loading设置为false,identifyState设置为true
  6. this.onGetDidDetails(this.BID) // 调用接口
  7. } else {
  8. this.isShowLoading = false // 当识别不到bid则loading消失。显示未识别内容
  9. this.identifyState = false // 显示未识别
  10. }
  11. },

以上实现扫码跳转,携带扫码成功的参数跳转至详情页面!