Directive @input: Hold until the user completes their query

As I navigate through my Vue learning curve, I've observed that the input field triggers an AJAX call (using axios) to YouTube with every keystroke entered. This means that even a single letter prompts a search query to be executed on the YouTube search API. While this method may work perfectly when searching a database by keywords, it seems inefficient for APIs like YouTube videos. It would be more optimal if the API call waited for the user to complete their search query before executing. Is there a directive or any other approach to ensure that the API call waits for the user to finish entering their search query before making the request to YouTube? By the way, during testing, I noticed that I reached my 1,000 limit on the YouTube API within just one hour.

This is the App.vue

<template>
  <SearchBar @emitTermSearch="onTermSearch"></SearchBar>
  <VideoList :videos="videos"></VideoList>
</template>

<script>
import axios from "axios";
import SearchBar from "./components/SearchBar";
const API_KEY = "hidden";
export default {
  name: "App",
  components: {
    SearchBar
  },
  data() {
    return {
      videos: []
    };
  },
  methods: {
    onTermSearch(emitTermSearch) {
      axios
        .get("https://www.googleapis.com/youtube/v3/search", {
          params: {
            key: API_KEY,
            type: "video",
            part: "snippet",
            maxResults: 2,
            order: "date",
            q: emitTermSearch
          }
        }.then(response => {
          this.videos = response.data.items;
        }).catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

This is the SearcBar.vue

<template>
  <h1>Please Search</h1>
  <div id="searchbar">
    <input @input="onInput" />
  </div>
</template>

<script>
export default {
  name: "SearchBar",
  methods: {
    onInput(event) {
      this.$emit("emitTermSearch", event.target.value);
    }
  }
};
</script>

Answer №1

To avoid using onInput with @input, consider triggering your event with @keyup.enter (or any other key) or including a button with a @click event.

Alternatively, you can implement a delay:

onInput(event) {
  setTimeout(() => {
    this.$emit("emitTermSearch", event.target.value);
  }, 700)
}

Answer №2

Check this out:

Vue.config.productionTip = false
Vue.config.devtools = false


new Vue({
  el: "#app",
  data: {
    typingInterval: 500,
    searchQuery: "",
    typingTimer: "",
  },
  methods: {
    searchData(){
      clearTimeout(this.typingTimer);
      if (searchQuery) {
          this.typingTimer = setTimeout(this.searchApi, this.typingInterval);
      }
     },
     
    searchApi(){
      console.log(`Fetching data for keyword: ${searchQuery}`);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input placeholder="search here" v-model="this.searchQuery" @keyup="searchData()">
</div>

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

Attempting to modify an object's property while maintaining reactivity, unfortunately encountering an issue with the property or method "vm" not being defined on the instance despite being referenced during the render

Up to this point, I've been attempting to set the value of an object property to false using @click='review.isActive = true'. However, it appears that Vue cannot detect these changes, causing the property to not be reactive. According to th ...

Implementing a 3D cylinder chart with ReactJS using Highcharts

I've been attempting to incorporate a cylinder 3D chart into my react component, but I keep encountering this error message. Error: Highcharts error #17: www.highcharts.com/errors/17/?missingModuleFor=cylinder missingModuleFor: cylinder The code in ...

Craft an Interactive Content Carousel

I have been searching for a responsive slide solution for two days with no luck, so I am reaching out for help. I am looking for a simple jQuery code for a slideshow that is lightweight and doesn't require a plugin. Here is the code for the slideshow: ...

Button Click Tracking Using Google Analytics for In-Page Searches

Is there a way to track Google Analytics In-Page search using the search code "KEYWORDS site:MYDOMAIN.com" without users immediately jumping to Google upon hitting Enter? I have heard about using Google Analytics hitCallback but I'm not sure how to i ...

What is the best method for removing node and then reinstalling it using nvm?

In my Mac, I have successfully installed Nodejs, but it was done using the usual method. However, in my new role, I've been asked to utilize NVM for Node installation. Can you guide me on the best approach to uninstall Node and then reinstall it with ...

Stream video files using NodeJS and seamlessly switch between audio tracks

I am looking to stream a video on my PC through a browser using nodejs. I found a helpful guide on how to achieve this using express, which can be found at this link: https://medium.com/better-programming/video-stream-with-node-js-and-html5-320b3191a6b6 (P ...

Having trouble with Vue @click.native not responding?

My navigation component looks like this: <template> <nav class="navbar navbar-default navbar-fixed-top"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar ...

Error in whatsapp-web.js: Unable to access properties of an unidentified object (reading 'default')

As I followed the step-by-step guide on how to use whatsapp-web.js, I encountered an issue. Here is the link to the guide const { Client } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const client = new Cl ...

Struggling to eliminate HTML tags from a string containing the 'aspNetHidden' CSS class

I have a web user control that is being compiled into HTML. The issue I am facing is that the HTML is returning with view states enclosed in DIVs with a class of aspNetHidden. These DIVs are causing problems with my page's design, so I am attempting t ...

Utilizing Mapbox-gl within a Vue.js single file component with Quasar-Framework integration

I'm attempting to incorporate a Mapbox-gl-js Map into a single file Vue component within the Quasar Framework, but I'm struggling to make it work. I've come across examples of Googlemaps with Vue and Mapbox with React, and I'm trying to ...

Encountering RangeError with the Number() function on my express.js server

I'm working with an HTML form that looks like this: <form class="" action="/" method="post"> <input type="text" name="num1" placeholder="First Number"> <input type= ...

Navigate directly to a particular tab using the URL

I came across a tab system built with jQuery online, but unfortunately, the creator who authorized its use is no longer reachable. That's why I'm turning to this platform for help. Here is the JavaScript code that controls the different tabs: w ...

Eliminating specific classes targeted by a jQuery attribute selector within the outcome of another jQuery attribute selector

I am facing a simple issue where I need to target all classes that end with a specific string on elements within a class ending with another specific string, and then remove those targeted classes. While the following code is close to what I want, it does ...

Refresh the vuex store values in real-time on the displayed page without the need

I am currently working on displaying variables from my backend that update automatically. To achieve this, I am utilizing Vuex store and nuxt.config.js for transferring the variables. API calls are used to modify the variables in the backend. However, I am ...

Error encountered while using the getJSON code syntax

Is there an issue with this code snippet? I am receiving a syntax error on line 1: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="http:/ ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

What is the best way to activate inline Javascript that has been added to my webpage? (Using ASP.NET webforms)

One interesting challenge I am facing involves a page section that is dynamically generated by the server. This particular section contains inline JavaScript code written by the server itself (This is ASP.NET webforms). The purpose of this JavaScript is to ...

Ways to continuously execute a JavaScript click event

Hello everyone! I've been a long time reader, but this is my first time posting. I'm completely new to this and need some help. How can I modify the code so that "ele.click();" will be triggered multiple times with a single press of the "Z" key? ...