vue實現掃碼功能
阿新 • • 發佈:2020-01-18
最近在專案中碰見一個開啟攝像頭掃碼的功能,專案最後打包成app,用的是hBuilder打的包,剛好hBuilder打包整合H5+sdk,就可以直接用人家的sdk了。
demo地址:vue-scan-demo
程式碼實現:
<template> <div class="scan"> <div id="bcid"> <div style="height:40%"></div> <p class="tip">...載入中...</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連線執行
效果圖:
通過這個例子,像其他的呼叫手機原生功能如:語音輸入、搖一搖、攝像頭、檔案系統、微信分享等也可以通過上述方式實現。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。