使用Vue3 完成電商產品篩選功能
最近在作小電商網站,有一頁打算放上所有商品,並用select製作篩選欄位,來記錄一下怎麼實踐以及我踩了哪些雷
框架:Vue3 composition API
Json檔案:有id, name, category等等項目,category是以陣列儲存,例如
category:["項鍊","戒指"]
構思
用html內建的select搭配v-model達到目的!
那要怎麼篩選資料呢?
我們要做的是有取出包含特定字串的內容,並且同步更新到dom上
關鍵字:
filter:篩選
computed:回傳數據
實作
Js
這邊為了把分類傳送給模板,我再加了一個category的json進去
import ProductData from'./data.json'
const category from './category.json'
const filter = ref("")
const returnProducts = computed(() => {
if (filter.value.length === 0) {
//如果沒有任何篩選項,直接返回原資料
return ProductData;
} else {
return ProductData.filter((item) => {
return item.category.includes(filter.value);
});
}
});
因為filter是響應性數據,記得要用filter.value
template
<select v-model="filter">
<option>所有內容</option>
<option v-for="cats in catogory">{{cats}}</option>
<div v-for=(item,index) in returnData">...</div>
使用select搭配option,要記得v-model綁定只能在select上面
綁定的效果>>選擇的項目會直接傳回給filter,再藉由filter的值讓我們進行篩選
並且用returndata來回傳資料
同步衍伸
除了includes以外,還有其他方法可以用來篩選
例如
- 檢查 item.category 是否包含 filter.value
return item.category.some(cat => cat === filter.value); - 檢查 item.category 中是否有任何值存在於 filter.value 中
return item.category.some(cat => filter.value.includes(cat)); - 搜尋關鍵字
return item.category.some(cat =>
cat.toLowerCase().includes(searchTerm)
some()
和 includes()
方法的性能差異?
some()
:
用於檢查數組中的元素是否「滿足指定條件」,在上面的例子中雖然我們使用===用作指定條件,但如果元素為數字,其實也可以使用 > , <= 等等。例如選擇價格區間。
條件是通過回調函數定義的,因此允許更複雜的邏輯。
一旦找到符合條件的元素就會立即返回
true
,並停止遍歷。- 性能取決於條件複雜度,每次迭代都要執行回調函數。
includes()
:
- 用於檢查數組中是否包含「特定值」。
不支持回調函數,只能用於簡單值的比較。
適用於需要精確匹配某個值的場景,效率更高。
可用於數組以及字串,因此關鍵字搜尋就會用到
Comments