Waiting for the user to complete their input in a Vue.js input field

I have a unique QR code generator on my website. I would like the QR codes to be generated dynamically based on user input, but not instantly. Instead, I want to wait for the user to finish typing before generating the QR code after one second. Here is the template for my setup:

<div class="app">
    <qrcode-vue :value="generatedQrCode"></qrcode-vue>
    <input type="text" v-model="qrCodeInput" />
</div>

Below is the script I am using:

import QrcodeVue from 'qrcode.vue';

export default {
    data() {
        return {
            generatedQrCode: '',
            qrCodeInput: '',
            isInputFunctionRunning: false
        }
    },
    watch: {
        async qrCodeInput() {
            if (this.isInputFunctionRunning) {
                return;
            }

            this.isInputFunctionRunning = true;

            await new Promise(r => setTimeout(r, 1000));

            this.generatedQrCode = this.qrCodeInput;

            this.isInputFunctionRunning = false;
        }
    }
    components: {
        QrcodeVue,
    },
}

However, it seems that the code is not functioning as intended. It is generating the QR code every second instead of waiting for the user to finish typing. My goal is to update the QR code only after the user has finished typing and one second has passed.

Answer №1

To properly handle input with a delay, the .lazy modifier should be used :

<input type="text" v-model.lazy="qrCodeInput" />

If a delay is desired before executing a function, consider implementing this debounce function:

import QrcodeVue from 'qrcode.vue';

function debounce (fn, delay) {
  var timeoutID = null
  return function () {
    clearTimeout(timeoutID)
    var args = arguments
    var that = this
    timeoutID = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}



export default {
    data() {
        return {
            genaratedQrCode: '',
            qrCodeInput: '',
            isInputFunctionRunning: false
        }
    },
    watch: {
        qrCodeInput:debounce(function() {
            if (this.isInputFunctionRunning) {
                return;
            }

            this.isInputFunctionRunning = true;

            this.genaratedQrCode = this.qrCodeInput;

            this.isInputFunctionRunning = false;
        },1000)
    }
    components: {
        QrcodeVue,
    },
}

This solution was inspired by the guidance provided in this answer;

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

Limitations of Typescript's Index Signature Templates

Currently, I have some Typescript Interfaces with repeated and similar fields. Here's an example: interface Foo { person1Name: string; person1Address: string; person2Name: string; person2Address: string; category: string; department: ...

Adjusting the waterlevel model attribute to its standard value

In my Sails.js project, I am looking to reset a model attribute back to its original default value. By default value, I mean the value specified using defaultsTo in the model file. I have attempted methods such as: model.update({id:exampleId}, {myAttrib ...

Why delay for asynchronous web service requests?

As I was exploring the MSDN documentation on WebServices, I came across information about calling a webservice and waiting for the response. Both this link and that link discuss this process, which seems to be a common trend in asynchronous implementations ...

Extract information from an array located inside a nested object

My aim is to calculate the length of the skills array for each user individually. To begin, I have this JSON data: const txt = `{ "Alex": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Generating unique spreadsheet identifiers in an HTML file

When it comes to displaying a chart using Google Sheets, I encounter an issue where the data is sourced from the same spreadsheet: function updateChart() { var ui = HtmlService.createHtmlOutputFromFile('ChartLine').setWidth(1350).setHeight(550) ...

Vue.js does not have the ability to toggle a font-awesome icon

I am having trouble toggling a font awesome icon based on a boolean value. It seems that the font-awesome icon stays on the screen even after it is drawn: Check out this link for reference HTML: <script src="https://unpkg.com/vue"></script> ...

Error: Cannot locate module: Vue not found, incorrect path specified

I am facing an issue with my webpack configuration. I have placed my webpack.config.js and node_modules in a subfolder. When attempting to run the command npm run build, I encounter the following error: ERROR in ../public/Vue/Components/Rating.vue Module n ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

Tips for creating a for loop in a .js script within MongoDB that allows for passing a variable containing the database name to a text file

In a .txt file, I have a list of database names as shown below: local test admin Is there a way to dynamically pass arguments instead of hardcoding them in .js scripts for mono go? db = db.getSiblingDB('test'); date = new Date() dat ...

The AngularJS framework does not support the Twitter Collection Grid feature

I'm currently facing an issue with implementing a Twitter Collection Grid on my website using an angularJS directive. The grid is not displaying correctly, as the pictures are stacking on top of each other instead of forming a grid layout. I've t ...

Tips for inserting a new choice into the v-select component of Vuetify

I need help loading data into a v-select using an API. I am attempting to include a new option labeled "all" with a value of 0, but the code I've tried doesn't seem quite right. Are there any alternative methods I could use to achieve this? ...

Nuxt - Auth module: Securely authenticating server-side requests

On a specific page, there is a requirement to load user-specific data using the fetch() hook. What is the process of accessing the authentication token on the server side in order to include it in this request? ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Print the content from the selected tab in AngularJS UI tab

In my AngularJS application, I have implemented nested tabs and encountered an issue. I am trying to enable users to print the selected content list from both parent and child tabs. Is there a way to achieve this so that when a user clicks on "print list ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

Eliminating certain buttons within Ember-leaflet-draw

Is there a way to remove specific buttons from the UI in my Ember application that are used for drawing lines, circles, and polygons? I am currently using Leaflet Draw in my project. Here is a snippet of my template.hbs: {{#leaflet-map onLoad=(action &apo ...

Struggling to apply the onclick function to an HTML element

I am working with an array of 10 elements that I need to shuffle and display, which my current code is able to do. However, the issue arises when I try to add functionality to show an alert message if any of the displayed array elements are clicked. The ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...

Unable to properly utilize environment variables on Vercel when using Nuxt framework

I'm encountering difficulties accessing my environment variables on Vercel. When I test the site on my localhost, everything works fine; however, once it's deployed to Vercel, the access to environment variables in my components and plugins direc ...

make the text in em font size larger

Incorporating HTML dynamically into a page using JavaScript is shown in the example below. _strInnerHtml += "<em>" + value.cate_name + " | " + value.city_name + "</em>"; _strInnerHtml += "<a href='#' class='activi ...