在Vue3中,我们可以使用v-debounce指令来实现搜索框输入防抖。首先,我们需要安装一个名为lodash.debounce的库,然后创建一个自定义指令v-debounce。
- 安装
lodash.debounce库:
npm install lodash.debounce --save
- 创建一个自定义指令
v-debounce:
// 导入lodash库 import { debounce } from 'lodash'; // 创建一个自定义指令v-debounce export default { // 注册指令 directives: { debounce: { // 当指令绑定的元素被插入到DOM时执行 inserted(el, binding) { // 获取用户传入的参数,例如延迟时间、事件处理函数等 const { value = 300, arg = 'input' } = binding.value; // 使用lodash的debounce方法创建防抖函数 const debouncedFn = debounce(binding.handler, value); // 将防抖函数赋值给元素的事件处理函数 el.addEventListener(arg, debouncedFn); }, // 当指令所在的组件被销毁时执行 unbind(el) { // 移除元素上的事件监听器 el.removeEventListener('input', el._v_debounce); } } } };
- 在Vue组件中使用
v-debounce指令:
<template> <div> <input type="text" v-model="searchText" v-debounce:input="handleSearch"> <ul> <li v-for="item in filteredList" :key="item.id">{{ item.name }}</li> </ul> </div> </template> <script> import vDebounce from './v-debounce'; // 导入自定义指令v-debounce export default { name: 'SearchComponent', directives: { debounce: vDebounce // 注册自定义指令v-debounce }, data() { return { searchText: '', // 搜索框中的文本 list: [ // 原始数据列表,用于模拟搜索功能 { id: 1, name: '苹果' }, { id: 2, name: '香蕉' }, { id: 3, name: '橙子' }, { id: 4, name: '葡萄' } ] }; }, computed: { filteredList() { // 根据搜索文本过滤数据列表的方法 return this.list.filter(item => item.name.includes(this.searchText)); } }, methods: { handleSearch() { // 搜索方法,根据过滤后的数据列表更新页面显示的内容 console.log('搜索内容:', this.searchText); // 打印搜索内容到控制台,方便调试和查看效果 } } }; </script>
这样,我们就实现了一个基于Vue3的搜索框输入防抖功能。当用户在搜索框中输入时,会触发防抖函数,延迟一段时间后再执行搜索方法。这样可以有效减少搜索方法的执行次数,提高性能。