1. If you
Encapsulate debelas.js in the utils directory:
let timeout = null
function debounce(fn, wait) {
if(timeout ! == null) clearTimeout(timeout) timeout =setTimeout(fn, wait)}export default debounce
Copy the code
Use the debounce. Js.
debounce.vue:
<template>
<div>
<input type="text" @input="debounceInput($event)"> <br/>
<button @click="clickMe()"</button> </div> </template> <script> import debounce from'. /.. /.. /utils/debounce.js'
export default {
data () {
return {
}
},
methods: {
clickMe(){
debounce(() => {
console.log('trigger')
}, 1000)
},
debounceInput(E) {
debounce(() => {
console.log(E.target.value)
}, 1000)
}
}
}
</script>
Copy the code
Shaking prevention Principle: When an event is triggered continuously and no event is triggered within a certain period of time, the event handler function is executed once.
For example, if no event is raised for 1000 milliseconds, the event handler will execute once.
Refer to the blog
VUE anti – shake and throttling the best solution – functional components