vue之input輸入框防抖debounce函數(shù)的使用方式
更新時間:2023年11月17日 10:59:32 作者:如果會御劍
這篇文章主要介紹了vue之input輸入框防抖debounce函數(shù)的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
方法一
這種方式很簡單,但是能實現(xiàn)一樣的功能。
<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()//需要防抖的函數(shù)
}, 500);
},
}
}
</script>方法二
這個方法是vue官網(wǎng)上的做法。
<template>
<div>
<input class="inputBox" type="text" placeholder="搜索項目名稱" v-model="searchValue">
</div>
<template><script>
export default{
data(){
return{
searchValue:''
}
}
//監(jiān)聽input輸入值變化
watch:{
searchValue:function(){
this.debouncedGetAnswer();
}
},
created(){
this.debouncedGetAnswer = this.debounce(this.getOfferList, 500);
//this.getOfferList是你查詢數(shù)據(jù)的函數(shù),也就是需要防抖的函數(shù)
},
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:''
}
}
//監(jiān)聽input輸入值變化
watch:{
searchValue:function(){
this.debouncedGetAnswer();
}
},
created(){
this.debouncedGetAnswer = this.debounce(this.getOfferList, 500);
//this.getOfferList是你查詢數(shù)據(jù)的函數(shù),也就是需要防抖的函數(shù)
},
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文件的使用方法
// 監(jiān)聽搜索框內(nèi)容的變化,等輸入完成才會執(zhí)行搜索函數(shù)=>即防抖
watch: {
searchValue: _debounce(function() {
this.page = 1
this.getJobFairList()
})
},
// 搜索,短時間內(nèi)連續(xù)點擊搜索按鈕只執(zhí)行一次搜索函數(shù)=>即節(jié)流
searchBtn: _throttle(function() {
if (this.searchValue) {
this.getJobFairList()
}
}),方法三是最近才更新的代碼,也是最新的代碼,建議使用方法三
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue3實戰(zhàn)教程之a(chǎn)xios的封裝和環(huán)境變量
這篇文章主要給大家介紹了關于vue3實戰(zhàn)教程之a(chǎn)xios的封裝和環(huán)境變量的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-02-02
vue學習筆記之指令v-text && v-html && v-bind詳解
這篇文章主要介紹了vue學習筆記之指令v-text && v-html && v-bind詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05

