-
Install lodash
# Yarn $ yarn add lodash # NPM $ npm install lodash --save Copy the code
-
use
// The first is the callback function, the second is the number of milliseconds to prevent jitter, and the third is the configuration // Generally, configure the first two parameters _.debounce(func, [wait=0], [options={}]) Copy the code
<template> <! -- Input box --> <input type="text" @input="onChange"/> </template> <script> // Import to use import _ from 'lodash' export default { data () { return { // Search for copywriting search: null}},methods: { // Define a shake-proof function to request the interface onSearch: _.debounce(function () { // Request the interface console.log(this.search) }, 1000), // Input changes onChange (e) { / / record this.search = e.target.value // Call the shaker function this.onSearch() } } } </script> Copy the code
-
The wrong way to use it so that it becomes a normal delay function, also note that _.debounce() returns a function and therefore needs to be called, hence the appended ().
// Input changes onChange (e) { // Define the anti-shake function _.debounce(function () { // Request the interface console.log(e.target.value) }, 1000) (the)}Copy the code