vue

vue实现搜索框模糊查询的方法有哪些

小亿
251
2023-08-03 23:54:29
栏目: 编程语言

Vue实现搜索框模糊查询的方法有以下几种:

  1. 使用computed属性:在Vue组件的computed选项中定义一个过滤函数,根据输入的关键词对数据进行筛选。
computed: {
filteredData() {
return this.dataList.filter(item => item.name.includes(this.keyword));
}
}
  1. 使用watch属性:在Vue组件的watch选项中监听输入框的变化,然后根据关键词进行筛选。
watch: {
keyword: {
handler(newKeyword) {
this.filteredData = this.dataList.filter(item => item.name.includes(newKeyword));
},
immediate: true
}
}
  1. 使用自定义指令:自定义一个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);
}
});
<template>
<input v-filter="filterData" />
</template>
methods: {
filterData(keyword) {
this.filteredData = this.dataList.filter(item => item.name.includes(keyword));
}
}

以上是一些常见的实现搜索框模糊查询的方法,具体可以根据自己的需求选择适合的方式。

0
看了该问题的人还看了