概要
今作成している機能で、WebアプリからQRコードを読み取り商品情報を取得し決済するという実装が実用になった
前提
Nuxt.js 2.4
SSR
vue-qrcode-reader
参考資料
実装方法
インストール
npm install --save vue-qrcode-reader
今回は、SSRなのでそのまま使用すると動かないみたいなので
プラグインを使用してクライアントサイドのみで実行するようにします。
plugin/vue-qrcode-reader.js
import Vue from 'vue'
import VueQrcodeReader from 'vue-qrcode-reader'
Vue.use(VueQrcodeReader)
nuxt.config.js
plugins: [
~
{ src: '~/plugins/vue-qrcode-reader', ssr: false }
],
<qrcode-stream>
を使用すれば簡単にQR読み取り機能が実装できる
onDecodeで読み取ったデータの処理を行うことができる
<template>
<div>
<p class="error">{{ error }}</p>
<p class="decode-result">
Last result: <b>{{ result }}</b>
</p>
<qrcode-stream @decode="onDecode" @init="onInit" />
</div>
</template>
<script>
export default {
layout: 'client/simple',
data() {
return {
result: '',
error: ''
}
},
methods: {
onDecode(result) {
this.result = result
},
async onInit(promise) {
try {
await promise
} catch (error) {
if (error.name === 'NotAllowedError') {
this.error = 'ERROR: you need to grant camera access permisson'
} else if (error.name === 'NotFoundError') {
this.error = 'ERROR: no camera on this device'
} else if (error.name === 'NotSupportedError') {
this.error = 'ERROR: secure context required (HTTPS, localhost)'
} else if (error.name === 'NotReadableError') {
this.error = 'ERROR: is the camera already in use?'
} else if (error.name === 'OverconstrainedError') {
this.error = 'ERROR: installed cameras are not suitable'
} else if (error.name === 'StreamApiNotSupportedError') {
this.error = 'ERROR: Stream API is not supported in this browser'
}
}
}
}
}
</script>