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

目录

使用到的功能点:

代码实现:


效果图:


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

⚠️:同一页面只能插入一个 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 组件,可以覆盖在部分原生组件上面。这两个组件也是原生组件,但是使用限制与其他原生组件有所不同。

代码实现:

// scan.vue. 扫码页
<view>
	<camera class="scan-area" @scancode="onScancode" @error="onError" mode="scanCode" device-position="back" flash="off">
		// <cover-image src="/static/image/scan-camera.gif"></cover-image>
        <image src="/static/image/scan-camera.gif"></image>
	</camera>

	<text>将二维码/条码放入框内,即可自动扫描</text>

	<view class="btn">	
		<view class="photo">
			<img @click="onPhoto" src="/static/image/photo.png" alt="" />
			<text>相册</text>
		</view>
	</view>
</view>

<script>
import * as utils from "@/utils/index";
export default({
    data(){
        return{
            hasScan: false, // false 还未跳转,true 已跳转一次
        }

    },
    onHide() { // 生命周期回调—监听页面隐藏
			this.hasScan = false
	},
	onUnload() { //生命周期回调—监听页面卸载
			this.hasScan = false
	},
    methods: {
			/**
			 * 扫码识别成功时触发,跳转至扫描详情页
			 * 防止扫码成功后页面多次跳转这里需要双重校验:
			 * 第一层校验:延迟跳转utils.throttle
			 * 第二层校验:使用变量控制hasScan是否跳转
			 * */
			onScancode: utils.throttle(function (e) {
				let bid = e.detail.result;
				if (!this.hasScan) {
					wx.navigateTo({
						url: `/sub_scan/scan_details/index?bid=` + encodeURIComponent(JSON.stringify(bid)),
						success: function(){
							this.hasScan = true
						}
					});
				}
			}, 1000),
    }
})

</script>

utils.throttle  方法:

// utils.js

/**
 * 防止小程序多次点击跳转
 * @param {*} obj 
 * @returns 
 */
export function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }

    let _lastTime = null

    // 返回新的函数
    return function () {
        let _nowTime = + new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments)   //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

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

// scan_detail.vue ,扫描详情页

onLoad(option) {
			this.BID = JSON.parse(decodeURIComponent(option.bid)); // 拿到参数bid

			if (!utils.isNullOrEmpty(this.BID) && this.BID.indexOf('did:bid') > -1) {
				// 当有bid的时候,loading先暂时加载着,直到接口内容返回后,才需要将loading设置为false,identifyState设置为true
				this.onGetDidDetails(this.BID) // 调用接口
			} else {
				this.isShowLoading = false // 当识别不到bid则loading消失。显示未识别内容
				this.identifyState = false // 显示未识别
			}
		},

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

猜你喜欢

转载自blog.csdn.net/q1ngqingsky/article/details/126389023