Vue實現模糊查詢的簡單示例
在Vue中實現模糊查詢,你可以使用JavaScript的filter和includes方法,結合Vue的v-for指令。下面是一個簡單的例子:
首先,你需要在你的Vue實例中定義一個數據數組和一個查詢字符串。
data() {
return {
items: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'],
query: ''
}
}然后,你可以在你的模板中使用v-for來遍歷這個數組,并使用v-model來綁定查詢字符串。
<input v-model="query" type="text" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item">
{{ item }}
</li>
</ul>在上面的代碼中,filteredItems是一個計算屬性,它會返回過濾后的數組。你可以使用JavaScript的filter和includes方法來實現模糊查詢。
computed: {
filteredItems() {
return this.items.filter(item => item.toLowerCase().includes(this.query.toLowerCase()));
}
}在上面的代碼中,filter方法會遍歷數組中的每個元素,并返回一個新的數組,該數組只包含滿足條件的元素。includes方法會檢查一個字符串是否包含另一個字符串。在這個例子中,我們使用toLowerCase方法將字符串轉換為小寫,以便進行不區(qū)分大小寫的查詢。
當使用Vue3實現模糊查詢時,你可以利用Vue的響應式特性和計算屬性來實現。下面是一個簡單的說明和代碼示例:
說明:
- 創(chuàng)建一個Vue3組件,并引入必要的依賴。
- 在組件的setup()函數中,定義數據和計算屬性。
- 使用v-model指令將輸入框的值綁定到數據屬性上。
- 定義一個計算屬性filteredItems,根據輸入框的值過濾數據數組。
- 在模板中使用v-for指令遍歷過濾后的數據數組,并顯示每個元素。
代碼示例:
<template>
<div>
<input v-model="searchQuery" type="text" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const items = ref([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
{ id: 4, name: 'Date' },
{ id: 5, name: 'Elderberry' }
]);
const searchQuery = ref('');
const filteredItems = computed(() => {
if (!searchQuery.value) return items.value;
return items.value.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
});
return { items, searchQuery, filteredItems };
}
};
</script>在上面的代碼中,我們首先導入了Vue3的ref函數,用于創(chuàng)建響應式引用。然后,在組件的setup()函數中,我們定義了兩個響應式引用items和searchQuery,分別表示數據數組和查詢字符串。接下來,我們定義了一個計算屬性filteredItems,根據輸入框的值過濾數據數組。最后,在模板中,我們使用v-model指令將輸入框的值綁定到searchQuery上,并使用v-for指令遍歷filteredItems數組,顯示每個項目的名稱。當輸入框的值發(fā)生變化時,計算屬性會自動更新,并觸發(fā)重新渲染。
以上就是Vue實現模糊查詢的簡單示例的詳細內容,更多關于Vue實現模糊查詢的資料請關注腳本之家其它相關文章!
相關文章
vue雙向錨點實現過程簡易版(scrollIntoView)
這篇文章主要介紹了vue雙向錨點實現過程簡易版(scrollIntoView),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

