使用vue-qr插件生成二维码 设置定时刷新或手动点击刷新二维码

832 阅读1分钟

vue-qr二维码插件使用介绍

官网介绍:www.npmjs.com/package/vue…

安装插件依赖

npm install vue-qr --save

主要代码

<div class="QRCode">
  <vue-qr :text="QRCodeText" :margin="0" colorDark="#000000" colorLight="#fff" :size="200"></vue-qr>
  <div class="refresh-btn">
    <i class="el-icon-refresh-right"></i>
    <div @click="getQRCode()">点击刷新</div>
  </div>
</div>
<script>
import { getQRCode } from '@/actions/user'
import vueQr from 'vue-qr'         // 引入插件

export default {
  name: 'accountInformation',
  components: {
    vueQr                       //引入组件
  },
  data() {
    return {
      QRCodeText: '',      // 需要转成二维码的数据
      expiredSeconds: 0,   // 自动刷新的间隔秒数
      timer: null
    }
  },
  mounted() {
    this.getQRCode()
  },
  beforeDestroy() {
    this.clearTimer()
  },
  methods: {
    async getQRCode() {
      // 调用后端接口获取信息
      const data = await getQRCode()
      // 后端返回的需要转成二维码的数据
      this.QRCodeText = data.encryptJson
      // 后端返回的定时自动刷新的秒数
      this.expiredSeconds = data.expiredSeconds
      
      // 清除之前的定时器
      if (this.timer != null) {
        clearInterval(this.timer)
        this.timer = null
      }

      // 重新设置定时器
      this.timer = setInterval(this.getQRCode, this.expiredSeconds * 1000)
    },
    // 清除定时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  }
}
</script>

参考效果图:

image.png

插件可修改的属性

image.png