Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided.

I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assistance completing this task.

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

export default {
  name: 'QRCode Generator',
  data() {
    return {
      custID: ref('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34574147405b595146745159555d581a575b59">[email protected]</a>'),
      getNow: ref(Date.now()),
      text: `${this.custID}?${this.getNow}`
    }
  },
  created() {
    setInterval(this.setQR, 3000)
  },
  methods: {
    getQR() {
      useQRCode(this.text)
    },
    setQR() {
      this.getNow = ref(Date.now())
    }
  }
}
</script>

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

<style scoped></style>

My current issue is that I am getting undefined?undefined for my QRCode string, which may be due to incorrect callouts and undefined data.

The expected functionality involves generating a dynamic custID based on customer information (commonly an email address), while the getNow variable represents a timestamp used to modify the data fed into the Barcode Generator every minute. Note that the interval is set at 3 seconds for immediate observation purposes...

The values of custID and getNow are concatenated in the text variable before being passed to the QRCode generator to update the displayed content, utilizing a ? separator.

Despite experimenting with advice from various sources like StackOverflow, Google, and VueSchool, I haven't achieved a solution yet.

This problem has consumed a considerable amount of time, and I am seeking guidance to finalize the implementation.

Answer №1

I made revisions to the code, now utilizing only the composition API instead of a combination of options and composition

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

const custID = ref('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7c6a6c6b70727a6d5f7a727e7673317c7072">[email protected]</a>');
const date = ref(Date.now());

const text = computed(() => `${custID.value}?${date.value}`);
const qrcode = useQRCode(text);
</script>

<template>
  <div style="display: flex; flex-direction: column;">
    <input v-model="custID" type="text">
    <input v-model="date" type="number">
    <span>{{text}}</span>
  </div>
  <img :src="qrcode" alt="QR Code">
</template>

This example demonstrates reactivity with inputs for both date and custID. However, these values can be dynamically set within function component logic rather than just through input fields.

Answer №2

I made some adjustments to your code structure by transitioning to the composition API and implementing a computed property for your text. Additionally, I included a cleanup process for the setInterval function when the component is no longer in use.

There were a few issues that could be resolved more efficiently using refs, so I switched those out. The main issue was ensuring that the useQRCode() function is called just once and provided with a dynamically updating ref or computed value for image changes.

<script setup>

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

const custID = ref('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d7c1c7c0dbd9d1c6f4d1d9d5ddd89ad7dbd9">[email protected]</a>')
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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for resolving classlist.toggle issues with my dark mode button

The code seems to work only the first time, but after activating light mode again, the sun stops appearing. How can I ensure that the 'bi-sun' class is added back every other click or when dark mode is not activated? function theme() { do ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Extracting the name of the file from the image's web address

I have created a simple Chrome extension for personal use and sharing with friends. I am dealing with URLs that have various formats, such as: i.imgur.com/abcd123.png or imgur.com/a2b3c78 or even i.imgur.com/herp321.png?1 All I need from these URLs are t ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...

How can JavaScript be used to dynamically load a second advertisement image immediately after the first ad image is successfully loaded?

Currently, I am working on ensuring that the 2nd ad image loads ONLY AFTER the 1st ad image has been loaded (please refer to the image with blue boxes). This is crucial as I have a CSS animation transitioning smoothly from the 1st ad image to the 2nd ad im ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

Each time new scripts are loaded, the Angular 13 window.ng.ɵcompilerFacade gets swapped out for a fresh

New Update: After observing the behavior of loading components/modules in my application, I have noticed a conflict arising between window.ng.ɵcompilerFacade and v13 compliance format when switching between Angular versions. The issue occurs when loading ...

Learn how to create a button that will only submit a value when clicked using Node.js and EJS

Currently in my ejs file, I have a button that sends a value to app.js instantly when the program runs. However, I want it to only submit the value when clicked by the user. <% notesArray.forEach((note,i) =>{ %> <div class="note"> ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

There seems to be an issue with React-hook-form and material-ui not retaining value changes in the onBlur() method

Stepping into the realm of react-hook-form is a new experience for me. I'm putting in effort to grasp everything, but there are still some pieces missing from the puzzle. Seeking assistance akin to Obiwan Kenobi! The Dilemma at Hand: An <Textfiel ...

Strategies for handling child and dynamic routes in web development

I'm currently using Nuxt2 to create a project structure that requires dynamic routes. As a result, I need more detailed navigation in order to make this work smoothly. Specifically, the route is: /lab/1/lad/2 Within the lab route (page), there are ...

What are the advantages of retrieving a complete category tree, including all categories and sub-categories, versus retrieving only the necessary branches as required?

My query is not centered around terminology accuracy, but rather on the goal of presenting a tiered structure consisting of categories, sub-categories, and sub-subcategories. In total, there are approximately 100 different categories and their respective ...

Adjust the ARIA value of a Bootstrap progress bar within a VueJS component on the fly

During the development of my website using VueJS and Bootstrap, I made the decision to utilize Vanilla Bootstrap instead of a specific VueJS framework like VueBootstrap or VueStrap. Currently, I am facing an issue while building a custom component that wr ...

What is the best way to animate elements so that they move in a circular motion?

My goal is to recreate the image shown in the picture: In case the image is blocked, you can view it here: The picture appears to have only one icon visible, but there are actually 4 icons. The image represents the path that the icons should follow. I&a ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Tips for keeping components mounted despite changes in the path

How can I maintain state in React routes to prevent unmounting when switching between them? In my application, it's crucial to keep the state intact during route changes. When changing routes, the respective components mount and unmount. How can this ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

Tips for fixing the 401 unauthorized error in Laravel with the help of Vue Axios

I am working on setting up CRUD operations in Laravel using Vue.js with Vue Axios and Vue Router. While the routing is functioning as expected, I'm encountering an issue when trying to save data using axios – the response I receive is a 401 unauthor ...

disable hover effect

Kindly visit the link below and click on 'Story': Upon mouseover, the animation can be observed: How can I remove this effect? The CSS I am using for this is as follows: .storypageThumb1 { float:left; width:175px; height:91px; ...

Tips for obtaining a JSON response from a RESTful API in AngularJS by utilizing the $resource service

I have been working on my AngularJS code, and although I am receiving a response in the console, I am having trouble storing it in an array or JSON format. angular.module('user', ['ngResource']). config(function($httpProvider){ $h ...