3
我已經在我的Vue開發中轉移到了使用Vuex狀態的一點點。過濾器Vuex狀態
以前,我有一個主要的Vue組件,它有搜索,項目數組循環和項目迭代本身。
正如我期望將單個組件拆分爲多個組件(搜索,項目列表和項目) - 我看到我無法更改子組件內的反應屬性。
那麼,我應該如何過濾我的物品清單。我是通過狀態變異還是通過子組件中的計算屬性來處理?
以前我是做
export default {
components: { Job },
data() {
return {
list: [],
categories: [],
states: states,
countries: countries,
keyword: '',
category: '',
type: '',
state: '',
country: '',
loading: true
}
},
mounted() {
axios.get('/api/cats.json')
.then(response =>
this.categories = response.data.data
)
axios.get('/api/jobs.json')
.then(function (response) {
this.list = response.data.data;
this.loading = false;
}.bind(this))
},
computed: {
filteredByAll() {
return getByCountry(getByState(getByType(getByCategory(getByKeyword(this.list, this.keyword), this.category), this.type), this.state), this.country)
},
filteredByKeyword() {
return getByKeyword(this.list, this.keyword)
},
filteredByCategory() {
return getByCategory(this.list, this.category)
},
filteredByType() {
return getByType(this.list, this.type)
},
filteredByState() {
return getByState(this.list, this.state)
},
filteredByCountry() {
return getByCountry(this.list, this.country)
}
}
}
function getByKeyword(list, keyword) {
const search = keyword.trim().toLowerCase()
if (!search.length) return list
return list.filter(item => item.name.toLowerCase().indexOf(search) > -1)
}
function getByCategory(list, category) {
if (!category) return list
return list.filter(item => item.category == category)
}
function getByType(list, type) {
if (!type) return list
return list.filter(item => item.type == type)
}
function getByState(list, state) {
if(!state) return list
return list.filter(item => item.stateCode == state)
}
function getByCountry(list, country) {
if(!country) return list
return list.filter(item => item.countryCode == country)
}
如果我的過濾器從應用搜索組件內或國家內的突變?
感謝這個,所以就這些干將被映射到每個組件,即過濾器組件和列表組件? –
@StevenGrant你需要在每個需要這些'getters'的組件中導入和使用'mapGetters'。你可以選擇,但你想要的。如果你想避免在許多組件中執行此操作,那麼我建議查找'mixins'。還要注意通過'mapGetters'而不是'getters'映射輔助函數的小錯誤,並且它們應該用引號引起來。 –
謝謝Amresh。我想我正在考慮這個問題以及我的過濾應該如何工作。因此,如果我的狀態包含缺省國家'all'以顯示所有項目,並且用戶選擇僅顯示美國項目的下拉菜單(作爲示例),則肯定需要將state.country值更改爲'US' ?這是一個突變或其他什麼? –