vue实现扫码功能

最近在项目中碰见一个打开摄像头扫码的功能,项目最后打包成app,用的是hBuilder打的包,刚好hBuilder打包集成H5+sdk,就可以直接用人家的sdk了。

demo地址:vue-scan-demo

代码实现:

<template> <div> <div> <div></div> <p>...载入中...</p> </div> <footer> <button @click="startRecognize">1.创建控件</button> <button @click="startScan">2.开始扫描</button> <button @click="cancelScan">3.结束扫描</button> <button @click="closeScan">4.关闭控件</button> </footer> </div> </template> <script type='text/ecmascript-6'> let scan = null; export default { data() { return { codeUrl: '', } }, methods: { //创建扫描控件 startRecognize() { let that = this; if (!window.plus) return; scan = new plus.barcode.Barcode('bcid'); scan.onmarked = onmarked; function onmarked(type, result, file) { switch (type) { case plus.barcode.QR: type = 'QR'; break; case plus.barcode.EAN13: type = 'EAN13'; break; case plus.barcode.EAN8: type = 'EAN8'; break; default: type = '其它' + type; break; } result = result.replace(/\n/g, ''); that.codeUrl = result; alert(result); that.closeScan(); } }, //开始扫描 startScan() { if (!window.plus) return; scan.start(); }, //关闭扫描 cancelScan() { if (!window.plus) return; scan.cancel(); }, //关闭条码识别控件 closeScan() { if (!window.plus) return; scan.close(); }, } } </script> <style lang="less"> .scan { height: 100%; #bcid { width: 100%; position: absolute; left: 0; right: 0; top: 0; bottom:3rem; text-align: center; color: #fff; background: #ccc; } footer { position: absolute; left: 0; bottom: 1rem; height: 2rem; line-height: 2rem; z-index: 2; } } </style>

预览:

打开Hbuilder,新建项目,将目录指向 /dist ,然后右键转换成移动App,真机usb连接运行

效果图:

vue实现扫码功能

通过这个例子,像其他的调用手机原生功能如:语音输入、摇一摇、摄像头、文件系统、微信分享等也可以通过上述方式实现。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/476bb0efd69a34a88d82a4d2baf775d5.html