vue項(xiàng)目中實(shí)現(xiàn)H5調(diào)取攝像頭掃碼掃一掃功能+生成可識(shí)別的條形碼

vue項(xiàng)目中實(shí)現(xiàn)H5調(diào)取攝像頭掃碼掃一掃功能+生成可識(shí)別的條形碼

案例描述:需求是生成條形碼并且在vue項(xiàng)目中實(shí)現(xiàn)掃一掃功能并不是拍照上傳后端識(shí)別那種

項(xiàng)目場(chǎng)景:?jiǎn)渭兊膆5項(xiàng)目溢十,沒(méi)辦法調(diào)用微信等封裝好的組件或者js因?yàn)橛行﹫?chǎng)景并不在微信自帶的瀏覽器里面

問(wèn)題描述:

生成條形碼使用vue-barcode

cnpm i vue-barcode -D


//在main.js中
import VueBarcode from 'vue-barcode';

Vue.component('barcode', VueBarcode)
//在對(duì)應(yīng)生成條形碼頁(yè)面
 <barcode :width="2" :value="code" :options="{format: 'CODE39', width: 2,displayValue: false}"></barcode>
 //value為輸入需要生成的code
 //value注意不要太長(zhǎng)因?yàn)樘L(zhǎng)的話生成的碼也很長(zhǎng)很密集,h5實(shí)現(xiàn)的掃一掃畢竟性能
 //不是很好太密集太長(zhǎng)識(shí)別不了,如果java生成的碼出現(xiàn)掃不
 //出來(lái)的情況告訴他試試調(diào)整成Code-128

第一步:因?yàn)閽叽ajs不支持vue組件注冊(cè)或者是引入等方式拣宰,就算是支持我感覺(jué)也很麻煩幻锁,所以這樣的話以動(dòng)態(tài)創(chuàng)建script的方法將掃碼js引入vue項(xiàng)目中

//動(dòng)態(tài)創(chuàng)建script的方法
 AddJs: function (url) {
    console.log(url,'url')
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.type = 'text/javascript'
      document.body.appendChild(script)
      script.onload = () => {
        resolve()
      }
    })
  },

第二步:在對(duì)應(yīng)的vue頁(yè)面調(diào)用方法將掃碼js引入

 methods: {
     init(){
        util.loadJs('https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js')  
    },
 },
 mounted(){
    this.init()
  }

第三步:在對(duì)應(yīng)的vue頁(yè)面中設(shè)置盛放掃碼的div盒子

<template>
 <div id="qr-reader" style="width:100%;height: 100%;"></div>
<template>

第四步:獲取當(dāng)前設(shè)備的攝像頭列表id并存儲(chǔ)為接下來(lái)使用

getCameras(){
        Html5Qrcode.getCameras().then(devices => {
        //判斷有沒(méi)有設(shè)備的攝像頭列表
          if (devices && devices.length) {
             // devices 是設(shè)備的攝像頭列表如果大于1的話默認(rèn)取后面攝像頭
              if(devices.length>1){
                this.cameraId = devices[1].id;
              }else{
                this.cameraId = devices[0].id;
              } 
          }
        }).catch(err => {
          // handle err
        });
    }

第五步:拿存儲(chǔ)的設(shè)備的攝像頭列表id啟動(dòng)掃碼

start(){
        this.html5QrCode = new Html5Qrcode('qr-reader')
        this.html5QrCode.start(
          this.cameraId,     // 上面獲取到的id
          {
            fps: 10,    // sets the framerate to 10 frame per second
            qrbox: 250  // sets only 250 X 250 region of viewfinder to
                        // scannable, rest shaded.
          },
          qrCodeMessage => {
            // do something when code is read. For example:
            if(qrCodeMessage){
                 //成功掃出碼qrCodeMessage為掃碼內(nèi)容
                 //掃碼成功記得關(guān)掉攝像
                 this.stop()
            }
           
          },
          errorMessage => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
          })
        .catch(err => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`);
        });
    },

第六步:關(guān)掉攝像頭

stop(){
        this.html5QrCode.stop().then(ignore => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        }).catch(err => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },

總體頁(yè)面:

使用vue實(shí)現(xiàn)h5掃碼功能

<template>
 <div class="scan">
     
     <div class="sectionview">
         <div id="qr-reader" style="width:100%;height: 100%;"></div>
     </div>
    
    <div class="footer">
    <van-button @click="getCameras" color="rgba(249, 185, 73, 1)">Obtain Access</van-button>
    </div>
 </div>
</template>
 
<script >
import util from '../common/js/util.js'
 export default {
 data() {
  return {
  codeUrl: '',
  cameraId:''
  }
 },
 beforeDestroy(){
     this.stop()
 },
 methods: {
   getCode(id){
      //跳轉(zhuǎn)頁(yè)面
   },
   init(){
        util.loadJs('https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js')
        //需要加載時(shí)間建議延時(shí)一點(diǎn)再獲取設(shè)備列表
        setTimeout(()=>{
            this.getCameras()
        },1000)
        
        
    },
    stop(){
        this.html5QrCode.stop().then(ignore => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        }).catch(err => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },
    start(){
        this.html5QrCode = new Html5Qrcode('qr-reader')
        this.html5QrCode.start(
          this.cameraId,     // retreived in the previous step.
          {
            fps: 10,    // sets the framerate to 10 frame per second
            qrbox: 250  // sets only 250 X 250 region of viewfinder to
                        // scannable, rest shaded.
          },
          qrCodeMessage => {
            // do something when code is read. For example:
            if(qrCodeMessage){
                 this.getCode(qrCodeMessage)
                 this.stop()
            }
           
          },
          errorMessage => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
          })
        .catch(err => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`);
        });
    },
    getCameras(){
        Html5Qrcode.getCameras().then(devices => {
          /**
           * devices would be an array of objects of type:
           * { id: "id", label: "label" }
           */
          if (devices && devices.length) {
              if(devices.length>1){
                this.cameraId = devices[1].id;
              }else{
                this.cameraId = devices[0].id;
              }
          
            
            console.log(this.cameraId,'cameraId')
            this.start()
            // .. use this to start scanning.
          }
        }).catch(err => {
          // handle err
        });
    }
    
    
  },
  mounted(){
    this.init()
  }

 }
</script>
<style lang="less">
 .scan {
    width: 100%;
    display: flex;
    flex-direction: column;
    height:100vh;
    overflow: hidden;
    .footer{
        width: 100%;
        display: flex;
        justify-content: center;
    }
    
    
 }
</style>

后期優(yōu)化改善研究參考文檔

如果對(duì)你有用不要忘記點(diǎn)贊收藏哦庐镐!
https://github.com/mebjas/html5-qrcode

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末朱嘴,一起剝皮案震驚了整個(gè)濱河市莫湘,隨后出現(xiàn)的幾起案子尤蒿,更是在濱河造成了極大的恐慌,老刑警劉巖幅垮,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件腰池,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡忙芒,警方通過(guò)查閱死者的電腦和手機(jī)示弓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)呵萨,“玉大人奏属,你說(shuō)我怎么就攤上這事〕甭停” “怎么了囱皿?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)忱嘹。 經(jīng)常有香客問(wèn)我嘱腥,道長(zhǎng),這世上最難降的妖魔是什么拘悦? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任齿兔,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘愧驱。我一直安慰自己,他們只是感情好椭盏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布组砚。 她就那樣靜靜地躺著,像睡著了一般掏颊。 火紅的嫁衣襯著肌膚如雪糟红。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,462評(píng)論 1 302
  • 那天乌叶,我揣著相機(jī)與錄音盆偿,去河邊找鬼。 笑死准浴,一個(gè)胖子當(dāng)著我的面吹牛事扭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播乐横,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼求橄,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了葡公?” 一聲冷哼從身側(cè)響起罐农,我...
    開(kāi)封第一講書(shū)人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎催什,沒(méi)想到半個(gè)月后涵亏,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蒲凶,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年气筋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片豹爹。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡裆悄,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出臂聋,到底是詐尸還是另有隱情光稼,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布孩等,位于F島的核電站艾君,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏肄方。R本人自食惡果不足惜冰垄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望权她。 院中可真熱鬧虹茶,春花似錦逝薪、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至要门,卻和暖如春虏肾,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背欢搜。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工封豪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人炒瘟。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓吹埠,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親唧领。 傳聞我的和親對(duì)象是個(gè)殘疾皇子藻雌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354