【uniapp】 手机端实现扫码识别

697 阅读1分钟

#【uniapp】 手机端实现扫码识别 网上先行者已经有很多插件和知名人士的作品了 只是可能需要一点调试 这里是我的调试感受和案例 注意 webview 的产生和销毁方式

 <template>
 	<view  id="barCodeBox"> </view>
 </template>

 <script>
 	let webView = null // webview容器
 	let barcode = null // 扫码框
 	export default {
 		data() {
 			return {
                             list:[],
 			}
 		},
 		onLoad(e) { 
 			setTimeout(() => {
 				this.scanCode()
 			}, 500)
 		},
 		onBackPress() {

 		},
 		beforeDestroy() {  
 			plus.webview.getWebviewById('barCodeBox').clear()
 			barcode.close();
 			webView.close();
 			barcode = null;
 			webView = null;
 		},
 		methods: {
 			scanCode() {
 				try {
					var th = this; 
 					webView = plus.webview.open(
 						'',
						'barCodeBox', {
 							top: '70px',
 							width: '100%',
 							height: '300px'
 						}
 					)
 					barcode = plus.barcode.create(
 						'barcode',
 						[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // 二维码 plus.barcode.QR  CODABAR
 						{
 							top: '0px',
 							left: '0px',
 							width: '100%',
 							height: '300px',
 							position: 'static',
 							scanbarColor: '#f1c01f',
 							frameColor: '#c0ff01'
 						}
 					) 
 					barcode.onmarked = (a, b) => {
 						console.log(a, b); 
 					}
 					plus.webview.getWebviewById('barCodeBox').append(barcode)
 					 
 					setTimeout(() => {
 						barcode.start()
 					}, 1000)
 				} catch (e) {
 					console.log(e); 
 				}
 				setInterval(() => {
 					try {
 						barcode.start()
 					} catch (e) {
 						console.log(e);
 					}
 				}, 2000)
 			}
 		}
 	}
 </script>