如何為VUE中的數據列表實現搜索過濾器?
使用Vue 3的Composition API實現搜索過濾功能,核心是通過v-model綁定搜索輸入和computed屬性動態過濾列表;2. 過濾時採用toLowerCase()實現不區分大小寫和部分匹配;3. 可通過watch監聽搜索詞並結合setTimeout實現300ms防抖,提升性能;4. 若數據來自API,可在onMounted中異步獲取並保持列表響應式;5. 最佳實踐包括使用computed而非方法、保留原始數據、為v-for添加key,以及在無結果時顯示“未找到”提示。該方案簡潔高效,適用於大多數場景。
Implementing a search filter for a list of data in Vue is a common and practical feature. Here's how to do it in a clean and reactive way using Vue 3 (Composition API), though the logic is similar in Vue 2 (Options API).

1. Basic Reactive Search Input with Computed Filtering
The key idea is to use a v-model
on the search input and a computed
property that filters your list based on the search term.
<template> <div> <input v-model="searchQuery" type="text" placeholder="Search items..." class="search-input" /> <ul> <li v-for="item in filteredItems" :key="item.id"> {{ item.name }} </li> </ul> </div> </template> <script setup> import { ref, computed } from 'vue' // Sample data const items = ref([ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' }, { id: 4, name: 'Blueberry' }, { id: 5, name: 'Avocado' } ]) // Reactive search query const searchQuery = ref('') // Computed property that filters items based on searchQuery const filteredItems = computed(() => { if (!searchQuery.value) return items.value return items.value.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ) }) </script>
2. Case-Insensitive and Partial Matching
The above example already handles case-insensitive matching by converting both the item name and search term to lowercase. This ensures "apple", "Apple", or "APPLE" all match.

You can expand the search to include multiple fields (eg, description
, category
) like this:
const filteredItems = computed(() => { if (!searchQuery.value) return items.value const query = searchQuery.value.toLowerCase() return items.value.filter(item => item.name.toLowerCase().includes(query) || item.description?.toLowerCase().includes(query) ) })
Note: Use optional chaining (
?.
) if some items might not have adescription
.
3. Debouncing for Performance (Optional)
If your list is large or you're making API calls, you may want to debounce the search input to avoid reactivity overhead on every keystroke.
You can use a library like Lodash ( lodash.debounce
) or implement a simple delay with setTimeout
:
<script setup> import { ref, watch } from 'vue' const searchQuery = ref('') const debouncedQuery = ref('') // Simulate debounce let timeout = null watch(searchQuery, (newVal) => { clearTimeout(timeout) timeout = setTimeout(() => { debouncedQuery.value = newVal }, 300) // 300ms delay }) const filteredItems = computed(() => { const query = debouncedQuery.value.toLowerCase() if (!query) return items.value return items.value.filter(item => item.name.toLowerCase().includes(query) ) }) </script>
Now filtering only happens 300ms after the user stops typing.
4. Using with API-Fetched Data
If your data comes from an API, you can still use the same pattern. Just make sure your list is reactive:
import { ref, computed, onMounted } from 'vue' const items = ref([]) const searchQuery = ref('') onMounted(async () => { const res = await fetch('/api/items') items.value = await res.json() }) const filteredItems = computed(() => { // same filter logic })
In this case, filtering happens locally after data is loaded.
5. Tips and Best Practices
- Use
computed
instead ofmethods
for filtering — it's cached and more efficient. - Keep the original list (
items
) unchanged; always filter from it. - For large datasets, consider pagination or server-side search.
- Add
key
tov-for
elements (you already did withitem.id
). - Provide feedback (eg, "No results found") when
filteredItems.length === 0
.
<div v-if="filteredItems.length === 0" class="no-results"> No items match your search. </div>
That's it. With just a reactive input and a computed filter, you can add powerful search functionality to any list in Vue. It's simple, efficient, and scales well for most use cases.
以上是如何為VUE中的數據列表實現搜索過濾器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

環境變量管理在Vue項目中至關重要,需根據構建工具選擇正確方式。 1.VueCLI項目使用VUE_APP_前綴的.env文件,通過process.env.VUE_APP_訪問,如.env.production;2.Vite項目使用VITE_前綴,通過import.meta.env.VITE_訪問,如.env.staging;3.兩者均支持自定義模式加載對應文件,且應將.env.local類文件加入.gitignore;4.始終避免在前端暴露敏感信息,提供.env.example供參考,並在運行時校

安裝ApolloClient和相關依賴包並根據Vue2或Vue3配置客戶端;2.在Vue3中通過provideApolloClient提供客戶端實例,在Vue2中使用VueApollo插件;3.使用useQuery和useMutation組合式API在組件中發起查詢和變更;4.通過變量和refetch實現動態數據獲取與刷新,可選輪詢更新;5.利用loading和error狀態優化用戶體驗,結合Suspense或防抖提升交互流暢性;6.通過HTTP鏈接頭添加認證信息,使用緩存、片段和查詢文件組織提

Usecomputed Properties WhenderiveReactiveValuesFordisPlay,AstheyAreCachedDandonlyre-evaluate-WhendependependencenciesChange; 2.UseWatchForexeCutingsIdeEffectSlikeCectSlikeCicallSorupDatingStorgeStorageInresetodatoreSeteToDatachanges

使用VueNative創建移動應用是利用Vue.js語法結合ReactNative實現跨平台開發的有效方式;2.首先配置開發環境,安裝Node.js、ExpoCLI,並通過命令npxcreate-react-native-appmy-vue-app--templatevue-native創建項目;3.進入項目目錄並運行npmstart,通過ExpoGo應用掃描二維碼在移動設備上預覽;4.編寫.vue文件組件,使用、和結構,注意採用小寫的ReactNative組件如view、text和button

teleportinvue3allowsrenderingAcomponent'stemplateInAdifferentDomLocationWhilePreservingItSlogicalPositionIntheComponentTree; 1.ItusestHecomponentWithatoTaToTributesPecifitutesPecifieingThetArgetDomnodeDormengetDomnode,supsas as asas as as s suesAs“ body” body'或“#modal-root”或“#modal-root”; 2.theteleport; theteleported;

功能組件在Vue2中用於創建無狀態、高性能的展示型組件,適用於僅依賴props的場景。 1.定義功能組件需設置functional:true,並通過render函數接收props和context返回VNode。 2.使用時像普通組件一樣註冊並傳入props和事件。 3.處理插槽需從context中獲取slots()和children。功能組件不適用於需要響應式數據、生命週期鉤子或v-model的場景。 Vue3中已移除functional選項,改用函數式寫法或簡潔的組合式組件替代,性能優化更依賴Comp

使用Vite創建支持TypeScript的Vue3項目;2.用defineComponent提供類型推斷;3.使用簡化代碼;4.用接口或類型定義props;5.用類型聯合正確聲明emits;6.在可組合函數中使用泛型;7.使用InjectionKey類型化provide/inject——通過這些步驟可實現類型安全、可維護的Vue3 TypeScript應用,最終構建出強大且可擴展的前端項目。

安裝Storybook可通過npxstorybook@latestinit自動完成,或手動安裝依賴並配置.storybook/main.js和preview.js;2.編寫故事文件(如Button.stories.js)定義組件不同狀態,使用Template綁定參數生成多個實例;3.利用Args和Controls實現屬性動態調整,提升交互測試效率;4.通過MDX文件整合文檔與故事,增強可讀性和協作性;5.建議將故事文件與組件共置、採用CSF格式、集成Chromatic進行視覺回歸測試,並使用裝飾
