app扫码识别并把数据传给后端然后跳转到首页
//首页
<span class="scan" ><img class="scans" @click="scann" src=""></span>
//扫码页
<template>
<div>
//码的样式
<div class="scan">
<div id="bcid">
<div style="height:40%"></div>
<p class="tip">...载入中...</p>
</div>
<button @click="back()">返回首页</button>
</div>
</div>
</template>
<script type='text/ecmascript-6'>
var scan = null
export default {
data() {
return {
// codeUrl: '',
token: localStorage.getItem('token'),
scan: null
}
},
mounted() {
this.startScan() //`进入页面就调取扫一扫
<!--console.log(localStorage.getItem('token'))-->
},
methods: {
// 创建扫描控件
startRecognize() {
// let scan = null
var that = this
if (!window.plus) return
this.scan = new plus.barcode.Barcode('bcid')
this.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(this.codeUrl)
//alert显示result已经获取
var url = ``
//后端要token和获取的数据result
console.log(url)
//这里console.log()是因为想看看数据是否拿到
that.$http.post(url).then(res => {
console.log(res)
//如果成功则关闭扫码然后弹出成功的值并跳转到首页
if(res.body.code == 0){
alert(res.body.msg);
that.closeScan()
that.cancelScan()
that.$router.push({path: '/'})
}else{
//反之则弹出没成功,也跳到首页
alert(res.body.msg);
that.closeScan()
that.cancelScan()
that.$router.push({path: '/'})
}
})
}
},
// 开始扫码
startScan() {
if (!window.plus) return
this.startRecognize()
setTimeout(() => {
this.scan.start()
}, 200)
},
//关闭扫描
cancelScan() {
if (!window.plus) return
this.scan.cancel()
},
// 关闭条码识别控件
closeScan() {
if (!window.plus) return
this.scan.close()
},
// 返回首页
back() {
this.closeScan()
this.cancelScan()
this.$router.push({path: '/'})
// console.log(scan)
}
},
// },
}
</script>
<style scope>
.scan {
height: 100%;
}
#bcid {
width: 100%;
height: 300px;
bottom: 3rem;
text-align: center;
color: #fff;
background: #ccc;
}
</style>
这一共有几处报错。 一开始报错的是说定义的scan没有找到,虽然我在script下面定义了的,但还是不生效,然后我就在data里面定义了一个scan:null 然后下面的都去data里面取 这个报错就解决了。然后发现还是报这个错,是一进来首页就报错,是因为我在写"返回首页"这个功能的时候由于扫码的界面没有关掉,所以我想着说在首页关掉,所以我写了一个关掉扫码,并且调用它(实际上也并没有起到作用,最后是在扫码页面调用才成功,然后我忘记删掉了...)。 然后还有一报错就是因为this的指向有问题(基础不扎实被这个绕晕了)把function换成箭头函数 或者定义that等于this都可以。