uniapp输入框防抖函数失效

13 篇文章 0 订阅
文章讲述了在uni-app中如何使用防抖函数(debounce)优化搜索组件的输入事件,避免频繁触发异步请求。通过将防抖函数应用到input事件处理函数,限制了searchAdvise方法的执行频率,提高了应用性能。
摘要由CSDN通过智能技术生成

搜索组件:

<view class="search-bar">
			<uni-search-bar placeholder="" class="search-bar-content" @confirm="search" v-model="searchVal"
				@input="input" :focus="true" bgColor="#EEEEEE" radius="50" cancelButton="always">
				<template v-slot:searchIcon>
					<uni-icons class="search-bar-icon" custom-prefix="bjsicons" type="bjs-search" size="30"
						@click="search"></uni-icons>
				</template>
			</uni-search-bar>
		</view>

外部防抖函数js:

export const debounce = (func, wait) => {
	let timerId = null;
	console.log(timerId);
	return function(){
	    let _This = this,
	        args = arguments;
	     if(timerId) clearTimeout(timerId);
	     timerId = setTimeout(function(){
	        func.apply(_This,args);
	        },wait);
	}
}

function throttle(){
	console.log("throttle");
}

module.exports = {
    throttle,
    debounce
}

调用防抖函数和搜索方法:注意这里debounce方法的写法。之前写在input函数体内,对searchAdvise进行防抖无效

search() {
				// 只有点击搜索才设置进搜索历史
				this.updateHistory(this.searchVal);
			},
			input: debounce(function (e) {
					this.searchVal = e;
					this.searchAdvise(this.searchVal);
			    }, 1000),
			async searchAdvise(keyword){
				const { list } = await unifyRequest(getSearchAdvise,keyword);
				this.searchList = list;
				console.log(list,this.searchList);
			},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UniApp输入框(`UI.input`)本身并不内置防抖或节流功能,但你可以通过在事件处理程序中手动实现这两个概念来优化输入事件的响应。防抖和节流是常见的性能优化技术,用于减少高频重复事件的执行次数,防止资源过度消耗。 **防抖(Debounce)**: - 防抖的目的是确保在一个输入停止后一段时间内,只执行一次特定的处理函数,比如发送网络请求。 - 当连续触发输入事件时,只有最后一次的事件会被处理,其余的会被忽略,直到输入暂停超过设定的时间(如200毫秒)。 **节流(Throttle)**: - 节流则是确保在一定时间内,最多执行某函数的指定次数,即使输入频繁触发。 - 它会在一定时间间隔(如500毫秒)内执行函数,如果在这段时间内又有新的输入事件,那么会取消之前正在执行的任务,等待下一次节流周期。 要实现这些效果,你可以在处理 `input` 事件的回调函数中使用 JavaScript 的内置方法,如下所示: ```javascript let timerId; const handleInput = (event) => { clearTimeout(timerId); timerId = setTimeout(() => { // 这里是你需要执行的处理逻辑,例如发送数据到后台 sendDataToServer(); }, 200); // 200毫秒的防抖时间(根据需求调整) }; UI.input.on('input', handleInput); ``` 或者使用第三方库(如lodash的debounce或lodash.throttle),这样代码更简洁: ```javascript import { debounce } from 'lodash'; UI.input.on('input', debounce(handleInput, 200)); ``` **相关问题--:** 1. 如何在UniApp中使用自定义防抖或节流函数? 2. 为什么要用防抖而不是节流来限制输入事件的响应? 3. 如果输入事件非常密集,单纯的防抖或节流会有什么问题?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值