<template>
  <div>
    <img  v-show ="isPng" :src="value" alt="二维码">
    <canvas v-show ="!isPng" :id ="id"></canvas>
  </div>
</template>
<script>
  import QRious from 'qrious'
  export default {
    mounted () {
      this.scope()
    },
    props: {
      value: String,
      size: {
        default: 100,
        type: Number
      },
      text: String,
      background: {
        default: '#fff',
        type: String
      },
      foreground: {
        default: '#000',
        type: String
      },
      isPng: {
        default: true,
        type: Boolean
      }
    },
    watch: {
      text (str) {
        this.update({
          value: str
        })
      },
      size (num) {
        this.update({
          size: num
        })
      },
      background (str) {
        this.update({
          background: str
        })
      },
      foreground (str) {
        this.update({
          foreground: str
        })
      }
    },
    methods: {
      update (obj) {
        this.qr.set(obj)
        this.$emit('input', this.qr.toDataURL())
      },
      scope () {
        this.qr = new QRious({
          element: document.getElementById(this.id),
          value: this.text,
          foreground: this.foreground,
          size: this.size,
          background: this.background
        })
        this.$emit('input', this.qr.toDataURL())
      }
    },
    data () {
      const UUID = (Math.random() * 1000).toString().split('.')[0]
  
      return {
        qr: {},
        id: UUID
      }
    }
  }
</script>
