在Vue.js中实现下拉框的模糊查询功能,通常涉及到以下几个基础概念:
以下是一个简单的Vue 3示例,展示如何在组件中实现下拉框的模糊查询:
<template>
<div>
<input type="text" v-model="searchQuery" placeholder="Search..." />
<select>
<option v-for="item in filteredOptions" :key="item.value" :value="item.value">
{{ item.text }}
</option>
</select>
</div>
</template>
<script>
import { ref, computed } from 'vue';
export default {
setup() {
const options = ref([
{ value: 'apple', text: 'Apple' },
{ value: 'banana', text: 'Banana' },
{ value: 'cherry', text: 'Cherry' },
// ...更多选项
]);
const searchQuery = ref('');
const filteredOptions = computed(() => {
return options.value.filter(option =>
option.text.toLowerCase().includes(searchQuery.value.toLowerCase())
);
});
return { searchQuery, filteredOptions };
}
};
</script>
import { ref, computed } from 'vue';
import { debounce } from 'lodash-es'; // 引入lodash-es库的debounce函数
export default {
setup() {
const options = ref([...]);
const searchQuery = ref('');
const filterOptions = debounce((query) => {
return options.value.filter(option =>
option.text.toLowerCase().includes(query.toLowerCase())
);
}, 300); // 设置300毫秒的防抖时间
const filteredOptions = computed(() => {
return filterOptions(searchQuery.value);
});
return { searchQuery, filteredOptions };
}
};
在这个示例中,我们使用了lodash-es
库中的debounce
函数来减少过滤操作的频率,从而提高性能。
通过上述方法,可以在Vue.js中实现一个高效且用户友好的下拉框模糊查询功能。
领取专属 10元无门槛券
手把手带您无忧上云