vue项目中防抖、节流的使用
common.js
// 防抖 export const debounce = function(method, delay) { // 定时器,用来 setTimeout var timer; // 返回一个函数,这个函数会在一个时间区间结束后的 delay 毫秒时执行 fn 函数 return function() { // 保存函数调用时的上下文和参数,传递给 fn var context = this; var args = arguments; // 每次这个返回的函数被调用,就清除定时器,以保证不执行 fn clearTimeout(timer); // 当返回的函数被最后一次调用后(也就是用户停止了某个连续的操作), // 再过 delay 毫秒就执行 fn timer = setTimeout(function() { method.apply(context, args); console.log(123456); }, delay); }; }; // 节流 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文件
// 滚动加载分页 <popup v-model="bankPicker" round position="bottom"> <div class="son-list"> <div class="search-cont"> <Search v-model="keyword" show-action shape="round" placeholder="请输入搜索关键词" @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++ //最后一次请求返回的数据为空或小于100条,不在请求,finished = true //根据业务需求更改 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