Using Vue Js to trigger an HTTP request when the user has finished typing

Here is an example of an input box I am working with:

<b-row>
    <b-col md="3"
        v-for="(header, index) in columns"
        :key="index"
    >
        <b-form-group>
            <b-form-input
                placeholder="Search"
                type="text"
                class="d-inline-block"
                @input="advanceSearch($event, header.field)"
            />
        </b-form-group>                            
    </b-col>
</b-row>

Whenever the user types something, I save the input to a variable called searchString:

advanceSearch(e, field) { 
    this.searchString.push({
        [field] : e
    });
    // http.post().then().catch(); // my http call
},

I would like to make the HTTP request only when the user has finished typing. Currently, it seems to be making a request after every keystroke.

Is there a way to achieve this in VUE JS?

Answer №1

Seems like you're looking to trigger the function both when the user is idle typing and when they focus out.

An unfocused input triggers the event change, making it easy to work with. You can even implement debouncing, which could look something like this:

export default {
  advanceSearch(e, field) { /* ... */ },

  // create a custom debounced search
  debouncedSearch(...args) {
    clearTimeout(this.debounceTimeout); 
    this.debounceTimeout = setTimeout(
      e => this.advanceSearch.apply(this, args),
      500 // debounce time
    );
  },

  // ...
}

In your Vue code, the input section should resemble the following. Note how the component now includes a change listener and uses the debounce function in the input handler instead of direct execution.

<b-form-input
  placeholder="Search"
  type="text"
  class="d-inline-block"
  @input="debouncedSearch($event, header.field)"
  @change="advanceSearch($event, header.field)"
/>

This code essentially sends an HTTP request when the user either types and then clicks out of the input box ("blur"), or pauses typing for half a second (you can adjust this value as needed).

Answer №2

I was able to achieve this functionality with minimal code and ease of use:

<template>
   <input v-model="searchInput" type="text" placeholder="Search...">
</template
<script>
export default {
    data() {
        return {
            searchInput: null
        };
    },
    watch: { 
        searchInput: function() {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.searchFunction();
            }, 500);
        }
    },
    methods: {
        searchFunction() {
           /* perform the necessary search operation here */
           // use this.searchInput as the search term
        },
    }
}
</script>

Using v-model along with searchInput eliminates the need to pass search parameters across multiple events and methods.

You can adjust the delay (currently set at 500 milliseconds) for a better user experience, typically anywhere between 300 to 600 milliseconds works well.

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

Increase the spacing between the column label and the x-axis label in a c3 chart

Take a look at the chart below, I'm attempting to create some additional spacing between the column labels and the x-axis label. https://i.sstatic.net/R7zqN.png I experimented with adding this CSS style: text.c3-axis-x-label { margin-top: 10 ...

Inject fresh variable values into the serialization process

Within my login form, I have fields for Username and Password. Upon clicking the login button, a Javascript function is triggered to make an ajax request to the login controller. To serialize the form data, I used the code snippet below: var parameters = ...

JavaScript Stopwatch Break

Below is the code snippet. How can a button be implemented to pause the timer and then resume it when the resume button is pressed? The // marks indicate where I plan to add my pause and resume functionality. Thank you in advance for your assistance! &l ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

Experiencing occasional "Cannot GET /" error when using node.js on Bluemix

My Bluemix services are giving me trouble. I keep encountering the error "Cannot GET /pathname" on my node.js express services. Strangely, this issue only occurs about one-third of the time. There is no logging or error messages in the application when thi ...

Save the outcome of the apollo query in a local state?

Imagine having a collection of condensed items associated with user IDs. When clicked, I aim to asynchronously fetch and display additional data using an Apollo query - like username, address, etc. How can I effectively "cache" or store this information lo ...

Zebra Calendar Alignment Problem

Currently working on an asp.net app and utilizing the Jquery Zebra DatePicker. Encountering an issue where when opening the form in a Jquery dialog, the calendar appears at the bottom of the page instead of within the dialog. A similar problem was discus ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Twilio Fax Reception: Blank Body Detected

I have embarked on my journey with Twilio's Programmable Fax API and successfully followed their getting started guide. However, upon receiving the fax, I encounter an issue where the request body appears as an empty object when logged to the console. ...

Look for a file within a directory based on its name without knowing the file extension

I am seeking a way to locate a specific file in a designated directory based on its name, without prior knowledge of its file extension. app.get("/test/:id", (req, res) => { const mongo_id = req.params.id; const file_path = ...

Script to pop up cancel alert box

There's a dilemma with this code - if you click CANCEL the first time the box pops up, it continues to run. I'm unsure of how to make it redirect to the underlying page when clicked on cancel for the first time. var numero= prompt ("Enter a nu ...

PHP's counterpart to the Javascript XMLHttpRequest

Recently, I have come across a PHP function that is quite interesting: function saveSnapshot() { header("Content-Type: application/JSON: charset=UTF-8"); global $CFG; $resString = "{\"Success\": \"True\"}"; $snapshotNa ...

How can we manually initiate the creation of a bootstrap dropdown using VueJS?

It appears that all the VueJS bootstrap components were designed for version 1.x and I encounter numerous errors (even with supposedly compatible packages) when attempting to use them with Vue 2.x Can the creation of bootstrap dropdowns on elements be tri ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

Best Practices for Converting TypeScript to JavaScript

What is the recommended approach to converting this JavaScript code into TypeScript? JAVASCRIPT: function MyClass() { var self = this, var1 = "abc", var2 = "xyz"; // Public self.method1 = function () { return "somethin ...

Call order for importing and exporting in NodeJS

This question is related to "code theory." Let's explore a scenario where I am utilizing the global namespace in a package. The structure includes a main entrypoint file, classes that are exported, and utility files used by the classes. Here's a ...

Step-by-step guide on displaying a fresh page within a JavaScript code

I've been working with XHTML, JSF, and JavaScript to develop a form that validates user input in selected fields when a button is clicked. The goal is to redirect the user to a different page called homepage.xhtml after successful validation. However, ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...

Utilizing the power of Web SQL Database with a dynamic Javascript loop

I'm currently facing a challenge that I could use some help with... While experimenting with Web SQL Databases, I've encountered an issue when trying to create a loop that functions correctly. Here's the code snippet I'm using: for ...

What are the essential files required to begin with d3.js?

Starting off with d3.js, I've downloaded the newest version from https://github.com/dc-js/dc.js/releases. Along with the d3.js file, there are plenty of other scripts located in the src and spec directories. Is it necessary to move all of these files ...