###### tags: `Vue` `店商網頁`
{%hackmd BJrTq20hE %}
# Vue店商網頁-產品多條件搜尋功能
既然是店商網頁那總要有搜尋功能吧!
1.有關鍵字搜尋
2.有最大與最小價格
## 該如何做到呢?
1.複製一個從api撈回來的陣列資料,這麼做的好處是為了減輕api伺服器的負擔外也是這個多條件搜索的關鍵。
2.使用重複的陣列資料進行過濾,例如透過關鍵字所濾出的資料,繼續以價格為條件進行過濾。
3.文字的搜尋使用indexOf與filter這個語法。
## 直接來看怎麼寫的吧?
1.在data中主要是以guestShowProduct作為呈現畫面的資料。
2.以guestProduct為過濾資料的起點。
3.guestShowSearch()(下方範例第32行)中一開始清空guestShowProduct,接著由第一個子函數infoFilter()(下方範例第8行)過濾資料。
4.infoFilter()使用forEach配上indexOf撈出資料,並存在guestShowProduct。
5.考慮到不是所有條件都會用到,所以在minFilter()與maxFilter()增加了如果沒有guestShowProduct沒有infoFilter()的資料就以guestProduct為起點(下方範例第17、25行)。
6.minFilter()與maxFilter()中因為參數帶null時在guestShowSearch()中最後的函式依然會運行所以特別在minFilter()與maxFilter()加上得if判斷式,使參數為null時不會有結果產生(下方範例第16、24行)
JS
```javascript=
data () {
return {
guestProduct: [],
guestShowProduct: [],
}
},
methods: {
infoFilter (info) {
this.guestProduct.forEach((item) => {
if (item.category.indexOf(info) !== -1 ||item.content.indexOf(info) !== -1 ||item.description.indexOf(info) !== -1 ||item.title.indexOf(info) !== -1) {
this.guestShowProduct.push(item)
}
})
},
minFilter (min, max, info) {
if (min) {
if (this.guestShowProduct.length === 0 && !info && !max) {
this.guestShowProduct = this.guestProduct
}
this.guestShowProduct = this.guestShowProduct.filter(item => min <= item.price || min <= item.origin_price)
}
},
maxFilter (max, min, info) {
if (max) {
if (this.guestShowProduct.length === 0 && !info && !min) {
this.guestShowProduct = this.guestProduct
}
this.guestShowProduct = this.guestShowProduct.filter(item => item.price <= max || item.origin_price <= max)
}
},
guestShowSearch (info, min, max) {
if (info || min || max) {
this.guestShowProduct = []
this.infoFilter(info)
this.minFilter(min)
this.maxFilter(max)
} else {
this.guestShowProduct = this.guestProduct
}
}
}
```