<template>
  <div class="qr-code">
    <div class="qr-code__img" :style="`width:${width}px;height:${height}px`">
      <img v-lazy="qrCode" alt="" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'

export default {
  name: 'QRCode',
  props: {
    url: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 175
    },
    height: {
      type: Number,
      default: 175
    }
  },
  data() {
    return {
      qrCode: ''
    }
  },
  watch: {
    url: {
      handler (nVal) {
        if (nVal) {
          this.makeQrcode(nVal)
        }
      },
      immediate: true
    }
  },
  methods: {
    makeQrcode(href) {
      QRCode.toDataURL(href)
        .then(url => {
          this.qrCode = url
        })
        .catch(err => {
          console.error(err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
.qr-code {
  &__img {
    > img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
}
</style>
