1.html部分
<template>
<div>
<div id="publicNav">
<!-- 這個地方用了vant的NavBar 導(dǎo)航欄 -->
<van-nav-bar title="掃一掃" left-arrow @click-left="onClickLeft">
<div slot="right" @click="onClickRight">
<div class="torch">
手電筒
</div>
</div>
</van-nav-bar>
</div>
<div>
<div class="scan">
<div id="container">
<p class="tip">...載入中...</p>
</div>
</div>
</div>
</div>
</template>
2.js部分
<script>
export default {
data() {
return { };
},
components: {},
mounted() {
this.startScan(); //進入頁面就調(diào)取掃一掃
},
created() {
this.startRecognize();
},
methods: {
onClickLeft() {
scan.cancel();//關(guān)閉
scan.close();//關(guān)閉條碼識別控件
this.$router.go(-1);
},
onClickRight() {
//打開手電筒(取反)
this.bFlash = !this.bFlash;
scan.setFlash(this.bFlash);
},
//創(chuàng)建掃描控件
startRecognize() {
let that = this;
if (!window.plus) return;
** scan這個全局變量我是定義在html里面的,因為點擊物理按鍵后退的時候會用到這個變量**
// 創(chuàng)建條碼掃描識別控件
scan = new plus.barcode.Barcode("container");
// 條碼識別成功
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, "");
alert(result);//彈出掃碼結(jié)果
scan.cancel(); //關(guān)閉掃描
scan.close(); //關(guān)閉條碼識別控件
}
},
//開始掃描
startScan() {
if (!window.plus) return;
this.startRecognize(); //創(chuàng)建控件
scan.start();
}
}
};
</script>
3.css
<style scoped>
#publicNav .van-nav-bar{
background: #0b0857;
height: 90px;
line-height: 90px;
}
#publicNav .van-nav-bar__title{
color: white;
font-size: 32px;
letter-spacing: 5px;
}
#publicNav .van-nav-bar .van-icon {
font-size: 40px;
color:white;
font-weight: bold;
top: 5px;
}
**上面的#publicNav的css必須寫在公共部分,因為我的設(shè)計稿是750的但使用vant的是375,所以我寫在公共部分去修改了單位大小**
.scan {
height: 100%;
}
.scan #container {
width: 100%;
position: absolute;
left: 0;
right: 0;
top: 90px; /*px*/
bottom: 0;
text-align: center;
color: #fff;
background: #ccc;
}
.torch {
font-size: 30px;
line-height: 80px;
color: white;
}
</style>