vue中使用loadsh的debounce防抖函數(shù)問題
使用loadsh的debounce防抖函數(shù)
<s-input placeholder="請輸入查詢關鍵字" prefix-icon="magnifier" v-model="content"></s-input>
<script>
import {debounce} from 'lodash'
export default {
watch: {
content: debounce(function(newVal, oldVal) {
this.search()
}, 1000)
},
methods:{
search(){
$axios.post('').then((res) => {})
}
}
}
</script>
<s-button @click="handleSave"></s-button>
<script>
import {debounce} from 'lodash'
export default {
methods:{
handleSave: debounce(function() {
//執(zhí)行方法
},1000),
}
}
</script>
debounce防抖函數(shù)的使用(js和vue)
debounch防抖函數(shù)主要應用場景,解決按鈕快速點擊,多次請求的問題和input輸入框多次請求的問題。接下來直接介紹在js和vue項目中的使用方式。
lodash工具庫地址:https://lodash.com/docs#debounce
三個參數(shù):
_.debounce(func, [wait=0], [options={}])options 有如下三個可選參數(shù)配置:
leading:指定在延遲開始前是否執(zhí)行 func(默認為 false)。maxWait:設置 func 允許被延遲的最大值。trailing:指定在延遲結束后是否執(zhí)行 func(默認為 true)
1.在js項目中的使用
(1)引用lodash工具庫:
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
(2)代碼:html:<div class="ceshi">點擊測試</div>
js:使用jq需引入jq庫,否則報錯
$(".ceshi").on("click",function(){
showAlert()
})
let showAlert = _.debounce(ceshiFun,400,
{'leading': true,
'trailing': false})
function ceshiFun(){
console.log("測試")
}2.在vue項目中的使用
(1)安裝。進入項目文件夾,執(zhí)行如下命令使用 npm 安裝 lodash:npm i --save lodash
(2)引入項目:import _ from 'lodash'
(3)在項目中使用示例:
<template>
<div id="test">
<button @click="btnClick">點擊</button>
</div>
</template>
<script>
import _ from 'lodash';
export default {
name: 'Test',
data () {
return {
}
},
methods:{
//按鈕點擊
btnClick() {
//顯示消息
this.showAlert('歡迎訪問hangge.com');
},
// 顯示消息時增加防抖(500毫秒延遲)
showAlert: _.debounce(function(message){
alert(message);
}, 500)
},
// 頁面創(chuàng)建時自動加載數(shù)據(jù)
created() {
}
}
</script>總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue.js配合$.post從后臺獲取數(shù)據(jù)簡單demo分享
今天小編就為大家?guī)硪黄獀ue.js配合$.post從后臺獲取數(shù)據(jù)簡單demo分享,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
詳解vue2.0+vue-video-player實現(xiàn)hls播放全過程
這篇文章主要介紹了詳解vue2.0+vue-video-player實現(xiàn)hls播放全過程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
vue中v-for和v-if一起使用之使用compute的示例代碼
這篇文章主要介紹了vue中v-for和v-if一起使用之使用compute的相關知識,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05
解決Vue警告Write?operation?failed:computed?value?is?readonl
這篇文章主要給大家介紹了關于如何解決Vue警告Write?operation?failed:computed?value?is?readonly的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-03-03
vue項目前端微信JSAPI與外部H5支付相關實現(xiàn)過程及常見問題
這篇文章主要介紹了vue項目前端微信JSAPI與外部H5支付相關實現(xiàn)過程及常見問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04

