Vue 输入事件方法中使用防抖失效问题

问题描述

有这样一个使用 Vue + ElementUI 制作的页面:
在这里插入图片描述
右上角是进行搜索的输入框,下面是所有的文件列表。要求在输入的时候搜索出与输入内容相同的文件名,考虑到性能影响,想要在输入事件方法中使用一个防抖函数:

<div class="search-input">
  <el-autocomplete
    v-model="searchValue"
    :fetch-suggestions="querySearch"
    :placeholder="$t('pleaseInput')"
    :trigger-on-focus="false"
    @input="handleInput"
    @select="handleSelect"
    @focus="showKeyboard"
    @blur="handleBlur"
  >
    <el-button slot="append" icon="el-icon-search" @click="searchProject"></el-button>
  </el-autocomplete>

input 事件方法 handleInput 中加入自己写的一个简单的防抖函数:

import { debounce } from '../../util/util.js';

methods: {
	handleInput() {
		debounce(function() {
			// 没有输出
			console.log('input');
		}, 500);
	}
}
// util.js
export function debounce(fn, delay) {
	let t = null;
	return function () {
		if (t !== null) {
			clearTimeout(t);
		}
		setTimeout(() => {
			fn.call(this);
		}, delay);
	}
}

结果发现 handleInput 方法中的测试代码没有输出,防抖失效。

解决方法

考虑到是利用闭包封装的一个防抖函数,我们把 handleInput 不用 ES6 的方式改写一下:

methods: {
	handleInput: function () {
		debounce(function () {
			console.log('input');
		}, 500);
	}
}

对比一下在原生 input 事件中会如何使用这个防抖函数:

inputElement.oninput = debounce(function () {
	console.log('input'); // 'input'
}, 500);

有没有发现什么问题,在 Vue 中想要使用防抖应该直接使用,而不是在方法内部使用!
handleInput 函数修改如下即可:

methods: {
	handleInput: debounce(function () {
		console.log('input'); // 'input'
	}, 500)
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值