daShangDao_scanBook/pages/upload/scan-isbn.nvue

106 lines
2.3 KiB
Plaintext

<template>
<view class="page">
<view id="barcodeContainer" class="barcode-container"></view>
<view class="close-btn" @click="goBack">
<text class="close-icon">✕</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
barcode: null,
scanned: false
}
},
onReady() {
this.initBarcode()
},
onUnload() {
this.destroyBarcode()
},
methods: {
initBarcode() {
if (typeof plus === 'undefined') {
uni.showToast({ title: '扫码初始化失败', icon: 'none' })
return
}
// 创建原生条码扫描控件,全透明无取景框
var options = {
top: '0px',
left: '0px',
width: '100%',
height: '100%',
frameColor: '#00000000',
scanbarColor: '#00000000',
background: '#00000000'
}
try {
this.barcode = new plus.barcode.Barcode('barcodeContainer', [plus.barcode.EAN13, plus.barcode.EAN8, plus.barcode.UPCA, plus.barcode.CODE128], options)
this.barcode.onmarked = (type, result) => {
if (this.scanned) return
this.scanned = true
if (result && result.length >= 10 && result.length <= 14) {
this.barcode.cancel()
uni.$emit('scan-isbn-result', result)
uni.navigateBack()
} else {
this.scanned = false
}
}
this.barcode.onerror = (e) => {
console.error('扫码错误:', e)
uni.showToast({ title: '扫码异常', icon: 'none' })
}
this.barcode.start()
} catch (e) {
console.error('Barcode init error:', e)
uni.showToast({ title: '扫码初始化失败', icon: 'none' })
}
},
destroyBarcode() {
if (this.barcode) {
try { this.barcode.cancel() } catch(e) {}
try { this.barcode.close() } catch(e) {}
this.barcode = null
}
},
goBack() {
this.destroyBarcode()
uni.navigateBack()
}
}
}
</script>
<style>
.page {
flex: 1;
background-color: #000;
position: relative;
}
.barcode-container {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
}
.close-btn {
position: fixed;
top: 60rpx;
left: 30rpx;
width: 60rpx;
height: 60rpx;
border-radius: 50%;
background: rgba(255,255,255,0.2);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.close-icon {
color: #fff;
font-size: 36rpx;
}
</style>