vue項(xiàng)目中防抖、節(jié)流的使用
common.js
// 防抖 export const debounce = function(method, delay) { // 定時(shí)器,用來 setTimeout var timer; // 返回一個(gè)函數(shù),這個(gè)函數(shù)會(huì)在一個(gè)時(shí)間區(qū)間結(jié)束后的 delay 毫秒時(shí)執(zhí)行 fn 函數(shù) return function() { // 保存函數(shù)調(diào)用時(shí)的上下文和參數(shù),傳遞給 fn var context = this; var args = arguments; // 每次這個(gè)返回的函數(shù)被調(diào)用,就清除定時(shí)器,以保證不執(zhí)行 fn clearTimeout(timer); // 當(dāng)返回的函數(shù)被最后一次調(diào)用后(也就是用戶停止了某個(gè)連續(xù)的操作), // 再過 delay 毫秒就執(zhí)行 fn timer = setTimeout(function() { method.apply(context, args); console.log(123456); }, delay); }; }; // 節(jié)流 export const throttle = function(method, delay, duration) { let timer = null, begin = new Date(); return function() { let context = this, args = arguments, current = new Date(); clearTimeout(timer); if (current - begin >= duration) { method.apply(context, args); begin = current; } else { timer = setTimeout(() => { method.apply(context, args); }, delay); } }; };
test.vue文件
// 滾動(dòng)加載分頁 <popup v-model="bankPicker" round position="bottom"> <div class="son-list"> <div class="search-cont"> <Search v-model="keyword" show-action shape="round" placeholder="請輸入搜索關(guān)鍵詞" @search="onSearch" @input="onInput" > <div slot="action" @click="onSearch">搜索</div> </Search> </div> <div class="bank-content" ref="bankContent"> <List v-model="loading" :finished="finished" finished-text="沒有更多了" @load="onLoad" > <div class="bank-item" :class="onSelectedCode==item.bankCnaps?'light-color':''" @click="selectedBank(item)" v-for="(item,index) in list" :key="index">{{item.bankName}}</div> </List> </div> </div> </popup> import { gthrottle, debounce } from "../utils/common.js"; data() { return { onSelected:'', // 選中銀行 onSelectedCode:'', // 選中銀行code keyword: '', pageSize: 100, pageNum: 1, list: [], loading: false, finished: false, } }, methods: { onInput: debounce(function() { this.onSearch() }, 1000), onSearch() { this.finished = false; this.loading = true; this.pageNum = 1; if (this.$refs.bankContent) this.$refs.bankContent.scrollTop = 0; this.list = []; this.onLoad() }, showBankItem() { if(this.readonly) { return; } this.bankPicker = true; this.pageNum = 1; this.keyword = ""; this.onSelected = this.form.depositAddress; this.onSelectedCode = this.form.bankCnaps; this.onSearch() }, onLoad() { this.getList() }, async getList() { try { let params = { pageNum: this.pageNum, pageSize: this.pageSize, keyword: this.keyword }; const result = await serviceApi.bankList(params); if (this.pageNum == 1) { this.list = []; this.list = result.data.list } else { this.list = this.list.concat(result.data.list) } this.loading = false; this.pageNum++ //最后一次請求返回的數(shù)據(jù)為空或小于100條,不在請求,finished = true //根據(jù)業(yè)務(wù)需求更改 if (result.data.list.length == 0 || result.data.list == null || result.data.list.length < 100) { this.finished = true return } } catch (error) { console.log(error); } }, }
sunshine15666

浙公網(wǎng)安備 33010602011771號(hào)