简体   繁体   中英

Avoid the Vue.js search to be updated in every letter typing

I've build a search component with vue.js 2.0 in my webapp. The problem that I have now is that it search on every type event. So let's say I want to search for samsung . It makes 7 request to my server (7 letters).

My input field looks like this:

<input
        class="input pr-4 pl-10 block"
        type="text"
        placeholder="Search for anything..."
        v-model="search"
        @keydown.enter="isOpen = false"
        @keydown.esc="isOpen = false"
        @input="onChange"/>

How do I make sure it only search when a word is typed (so it makes 1 request to my server)

You normally solve these kind of problems by building in somewhat of a delay or a so called debounce . By debouncing a function, you basically say "Execute this function after this many ms, unless the debounced function is invoked again". If the user types fast enough, this saves some requests to your server. The delay should be small enough to not be that noticeable to the user, but should be large enough to prevent unnecessary spam to your server. In this example I use lodash' debounce function ( documentation ).

If your search takes too long in general, debouncing will help reduce the bleeding, but will not stop it. Consider adding an actual search button and trigger search when clicking that button and/or pressing enter. You can also create a low-cost search for "suggestions" and a regular search that searches through everything, similar to what you see when you type in the search box on, say, Wikipedia.

<template>
  <input
    class="input pr-4 pl-10 block"
    type="text"
    placeholder="Search for anything..."
    v-model="search"
    @keydown.enter="isOpen = false"
    @keydown.esc="isOpen = false"
    @input="debouncedOnChange"
  />
</template>

<script>
import _debounce from 'lodash.debounce';

export default {
  name: 'search',
  data () {
    return {
      search: '',
      isOpen: false
    }
  },

  computed: {
    debouncedOnChange () {
      return _debounce(this.onChange, 700);
    }
  },

  methods: {
    onChange () {
      // do something with this.search
    }
  }
}
</script>

编辑Vue模板

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM