vue實(shí)現(xiàn)搜索框模糊查詢的方法有哪些

vue
小億
353
2023-08-03 23:54:29

Vue實(shí)現(xiàn)搜索框模糊查詢的方法有以下幾種:

  1. 使用computed屬性:在Vue組件的computed選項(xiàng)中定義一個(gè)過(guò)濾函數(shù),根據(jù)輸入的關(guān)鍵詞對(duì)數(shù)據(jù)進(jìn)行篩選。
computed: {
filteredData() {
return this.dataList.filter(item => item.name.includes(this.keyword));
}
}
  1. 使用watch屬性:在Vue組件的watch選項(xiàng)中監(jiān)聽(tīng)輸入框的變化,然后根據(jù)關(guān)鍵詞進(jìn)行篩選。
watch: {
keyword: {
handler(newKeyword) {
this.filteredData = this.dataList.filter(item => item.name.includes(newKeyword));
},
immediate: true
}
}
  1. 使用自定義指令:自定義一個(gè)v-filter指令,通過(guò)鉤子函數(shù)bind和update監(jiān)聽(tīng)輸入框的變化,然后根據(jù)關(guān)鍵詞進(jìn)行篩選。
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));
}
}

以上是一些常見(jiàn)的實(shí)現(xiàn)搜索框模糊查詢的方法,具體可以根據(jù)自己的需求選擇適合的方式。

0