二维码生成器未按预期工作

问题描述 投票:0回答:1

我正在尝试创建一个每分钟都在变化的二维码生成器。我已经创建了以下代码,但收到了一些错误,只需要一些帮助来完成这最后的工作。

<script>
import { useQRCode } from '@vueuse/integrations/useQRCode'
import { ref } from 'vue'

const custID = ref('[email protected]')
let getNow = Date.now()

export default {
  name: 'QRCode Generator',
  data() {
    return {
      text: `${custID.value}?${getNow.value}`
    }
  },
  created() {
    setInterval(this.setQR, 3000)
  },
  methods: {
    getQR() {
      useQRCode(this.text)
    },
    setQR() {
      ;(getNow.value = Date.now()), this.getQR() // Vue Plugin did this, no idea why?
    }
  }
}
</script>

<template>
  <input id="text" v-model="text" type="text" />
  <img :src="this.getQR()" alt="QR Code" />
</template>

<style scoped></style>

目前,我对

Uncaught TypeError: Cannot create property 'value' on number
变量得到
getNow
,但二维码实际上并未显示,可能是因为我调用错误,并且缺少一些数据。

它应该工作的方式是

custID
是从客户数据生成的,因此它将是动态的(很可能是电子邮件地址),但是
getNow
只是我用来修改数据的时间戳馈送到条形码生成器,以每分钟更改它。然而,当前间隔设置为 3 秒,这样我就可以看到它正在运行,无需等待...

两个

custID
getNow
值组合在
text
变量中,并传递到 QRCode 生成器以更改显示的内容,我用
?
将它们分开。

我尝试了 StackOverflow、Google 和 VueSchool 的一些建议,但没有成功。

我已经研究这个有一段时间了,只需要一些帮助将最后一块调整到位。

javascript vue.js vuejs3 qr-code
1个回答
0
投票

我稍微修改了您的结构,转向组合 API 并为您的

computed
引入了
text
值。我还添加了卸载组件时对
setInterval
的清理。

有几个问题用

ref
更容易解决,所以我升级了这些问题。主要问题是
useQRCode()
应该被调用一次,并传递一个
ref
computed
,当你想要改变图像时,它会被更新。

<script setup>

import { useQRCode } from "@vueuse/integrations/useQRCode"
import {tryOnUnmounted} from "@vueuse/core"
import {computed, ref} from "vue"

const custID = ref('[email protected]')
const getNow = ref(Date.now())

const text = computed(() => {
  return `${custID.value}?${getNow.value}`
})

const qrCode = useQRCode(text)

function setNow() {
  getNow.value = Date.now()
}

let intervalId = setInterval(setNow, 10000);

tryOnUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
})

</script>

<template>
  <input id="text" v-model="text" type="text" />
  <img :src="qrCode" alt="QR Code" />
</template>
© www.soinside.com 2019 - 2024. All rights reserved.