vue之input输入框防抖debounce函数的使用方式
作者:如果会御剑
这篇文章主要介绍了vue之input输入框防抖debounce函数的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
方法一
这种方式很简单,但是能实现一样的功能。
<template>
<div>
<input class="inputBox" type="text" placeholder="搜索项目名称" v-model="searchValue" @keyup.enter="searchBtn" @input="searchBtn">
</div>
</template><script>
let timers = null;
export default{
data(){
return{
searchValue:''
}
}
methods:{
searchBtn(){
clearTimeout(timers)
timers = setTimeout(() => {
this.getOfferList()//需要防抖的函数
}, 500);
},
}
}
</script>方法二
这个方法是vue官网上的做法。
<template>
<div>
<input class="inputBox" type="text" placeholder="搜索项目名称" v-model="searchValue">
</div>
<template><script>
export default{
data(){
return{
searchValue:''
}
}
//监听input输入值变化
watch:{
searchValue:function(){
this.debouncedGetAnswer();
}
},
created(){
this.debouncedGetAnswer = this.debounce(this.getOfferList, 500);
//this.getOfferList是你查询数据的函数,也就是需要防抖的函数
},
methods:{
//防抖
debounce(fn, delay = 500){
let timer = null;
return function() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
}
</script>方法三
1.封装一个模块,引入即可,在utils新建一个js文件,名称随便
<template>
<div>
<input class="inputBox" type="text" placeholder="搜索项目名称" v-model="searchValue">
</div>
<template><script>
export default{
data(){
return{
searchValue:''
}
}
//监听input输入值变化
watch:{
searchValue:function(){
this.debouncedGetAnswer();
}
},
created(){
this.debouncedGetAnswer = this.debounce(this.getOfferList, 500);
//this.getOfferList是你查询数据的函数,也就是需要防抖的函数
},
methods:{
//防抖
debounce(fn, delay = 500){
let timer = null;
return function() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
}
</script>2.在需要的vue文件引入即可使用
import { _throttle, _debounce } from '@/utils/throttle'3.在vue文件的使用方法
// 监听搜索框内容的变化,等输入完成才会执行搜索函数=>即防抖
watch: {
searchValue: _debounce(function() {
this.page = 1
this.getJobFairList()
})
},
// 搜索,短时间内连续点击搜索按钮只执行一次搜索函数=>即节流
searchBtn: _throttle(function() {
if (this.searchValue) {
this.getJobFairList()
}
}),方法三是最近才更新的代码,也是最新的代码,建议使用方法三
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
