Vue实现搜索框模糊查询的方法有以下几种:
- 使用computed属性:在Vue组件的computed选项中定义一个过滤函数,根据输入的关键词对数据进行筛选。
computed: { filteredData() { return this.dataList.filter(item => item.name.includes(this.keyword)); } }
- 使用watch属性:在Vue组件的watch选项中监听输入框的变化,然后根据关键词进行筛选。
watch: { keyword: { handler(newKeyword) { this.filteredData = https://www.yisu.com/ask/this.dataList.filter(item => item.name.includes(newKeyword)); }, immediate: true } }
- 使用自定义指令:自定义一个v-filter指令,通过钩子函数bind和update监听输入框的变化,然后根据关键词进行筛选。
Vue.directive('filter', {
bind(el, binding) {
el.addEventListener('input', function() {
const keyword = el.value;
binding.value(keyword);
});
},
update(el, binding) {
const keyword = el.value;
binding.value(keyword);
}
});
methods: {
filterData(keyword) {
this.filteredData = https://www.yisu.com/ask/this.dataList.filter(item => item.name.includes(keyword));
}
}
以上是一些常见的实现搜索框模糊查询的方法,具体可以根据自己的需求选择适合的方式。