Vue.js 3 + TypeScriptでvue-qrcodeを導入する

こんにちは!kossyです!




さて、今回はVue.js 3 + TypeScriptでvue-qrcodeを導入する方法について、ブログに残してみたいと思います。



環境

vue/cli 4.5.9
vue 3.1.2
typescript 3.9.7
vue-qrcode 2.0.0-rc




導入

以下のコマンドを実行します。

$ npm install vue@next qrcode @chenfengyuan/vue-qrcode@next

npm install が完了したら、main.tsを編集します。

import { createApp } from 'vue'
import App from '@/App.vue'
import VueQrcode from '@chenfengyuan/vue-qrcode'

const app = createApp(App)

if (VueQrcode.name) {
  app.component(VueQrcode.name, VueQrcode)
}

app.mount('#app')

if文で条件分岐しているのは、VueQrcode.nameの型が string | undefined になっていて、app.component関数の第一引数の型と合わないとTypeScript Compilerに指摘を受けるためです。

f:id:kossy-web-engineer:20210703215421p:plain

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

と言われてしまっているため、if文で分岐をいれて指摘をされないようにしています。

あとは、以下のようにtemplateタグで定義すればQRコードを表示することができます。

<vue-qrcode :value="qrCode" />

"qrCode"にはuriを格納している想定です。


大いに参考にさせていただいたサイト

GitHub - fengyuanchen/vue-qrcode: QR code component for Vue.js