語境
我正在嘗試使用過濾器側邊欄創建檔案串列視圖。檔案存盤在 Firestore 中,我使用 Nuxt 和 Vuex 來獲取和存盤檔案。
export const getters = {
plants: (state) => state.plants
}
export const mutations = {
SET_PLANTS(state, payload) {
state.plants = payload
}
}
export const actions = {
async fetchPlants({ commit }, queryArray) {
const docsRef = collection(db, 'plants')
let snapshot;
if (queryArray) {
const q = query(docsRef, where(...queryArray))
snapshot = await getDocs(q)
} else {
snapshot = await getDocs(docsRef)
}
const results = []
snapshot.forEach((doc) => {
results.push({ ...doc.data(), id: doc.id })
})
commit('SET_PLANTS', results)
}
}
然后,在我的 ListView 組件中,我獲取資料:
export default {
async fetch({ store }) {
try {
await store.dispatch('plants/fetchPlants')
} catch (err) {
console.log(err)
}
},
computed: {
plants() {
return this.$store.getters['plants/plants']
}
}
}
并使用一個簡單的v-for回圈來輸出資料:
<div v-for="plant in plants" :key="plant.id">
<h3>{{ plant.name }}</h3>
<p>{{ plant.description }}</p>
<span v-for="(value, index) in plant.properties" :key="index">
{{ value }}
</span>
</div>
v-for注意接受植物屬性的嵌套回圈。這些包括諸如“需要很少的水”、“需要很少的陽光”等內容。
問題
我想在 ListView 組件中創建一個過濾器側邊欄,允許用戶使用每個植物的復選框根據植物的屬性過濾植物。
正如您可能已經看到的,我已經queryArray在操作中設定了引數fetchPlants:
if (queryArray) {
const q = query(docsRef, where(...queryArray))
snapshot = await getDocs(q)
}
此引數可能如下所示:['water', '==', 'Needs little water']
但是,此設定僅允許應用 1 個過濾器。如何where()使用復選框將多個子句正確鏈接在一起?
uj5u.com熱心網友回復:
如果你queryArray看起來像這樣:
const queryArray = [
['water', '==', 'Needs little water'],
['light', '==', 'Needs little sunlight'],
]
然后您必須where()為每個欄位添加一個,如下所示:
const q = query(docsRef, ...queryArray.map((item) => where(item[0], item[1], item[2])))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450877.html
