vue使用lodash中debounce(防抖函數(shù))的幾種方法實(shí)現(xiàn)
1、安裝
npm i --save lodash.debounce
2、引入
import debounce from 'lodash.debounce'
3、使用
<van-search v-model="searchValue" placeholder="輸入姓名或工號" @input='handleInput' />
第一種:
handleInput: debounce(function (val) {
console.log(val)
}, 200)
第二種:
handleInput(val) {
console.log(val)
}
created() {
this.handleInput = debounce(this.handleInput, 200) // 搜索框防抖
}
這兩種使用方式效果一樣
觀察者防抖:
<template>
<input v-model="value" type="text" />
<p>{{ value }}</p>
</template>
<script>
import debounce from "lodash.debounce";
export default {
data() {
return {
value: "",
};
},
watch: {
value(...args) {
this.debouncedWatch(...args);
},
},
created() {
this.debouncedWatch = debounce((newValue, oldValue) => {
console.log('New value:', newValue);
}, 500);
},
beforeUnmount() {
this.debouncedWatch.cancel();
},
};
</script>
事件處理器防抖:
<template>
<input v-on:input="debouncedHandler" type="text" />
</template>
<script>
import debounce from "lodash.debounce";
export default {
created() {
this.debouncedHandler = debounce(event => {
console.log('New value:', event.target.value);
}, 500);
},
beforeUnmount() {
this.debouncedHandler.cancel();
}
};
</script>
為什么不在method中寫好方法,在template中直接調(diào)用,就像這樣
<template>
<input v-on:input="debouncedHandler" type="text" />
</template>
<script>
import debounce from "lodash.debounce";
export default {
methods: {
// Don't do this!
debouncedHandler: debounce(function(event) {
console.log('New value:', event.target.value);
}, 500)
}
};
</script>
組件使用 export default { … } 導(dǎo)出的 options 對象,包括方法,會(huì)被組件實(shí)例重用。
如果網(wǎng)頁中有 2 個(gè)以上的組件實(shí)例,那么所有的組件都會(huì)應(yīng)用 相同 的防抖函數(shù) methods.debouncedHandler — 這會(huì)導(dǎo)致防抖出現(xiàn)故障。
到此這篇關(guān)于vue使用lodash中debounce(防抖函數(shù))的幾種方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)vue debounce防抖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vite創(chuàng)建項(xiàng)目的實(shí)現(xiàn)步驟
隨著 Vite2 的發(fā)布并日趨穩(wěn)定,現(xiàn)在越來越多的項(xiàng)目開始嘗試使用它。本文我們就介紹了Vite創(chuàng)建項(xiàng)目的實(shí)現(xiàn)步驟,感興趣的可以了解一下2021-07-07
electron+vue實(shí)現(xiàn)div contenteditable截圖功能
這篇文章主要介紹了electron+vue實(shí)現(xiàn)div contenteditable截圖功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
vue.js項(xiàng)目使用原生js實(shí)現(xiàn)移動(dòng)端的輪播圖
這篇文章主要為大家介紹了vue.js項(xiàng)目中使用原生js實(shí)現(xiàn)移動(dòng)端的輪播圖,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
Vue?2中實(shí)現(xiàn)CustomRef方式防抖節(jié)流
這篇文章主要為大家介紹了Vue?2中實(shí)現(xiàn)CustomRef方式防抖節(jié)流示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

