I've moved on a little in my Vue development to looking at using Vuex for state.
Previously, I had one master Vue component that had search, an array of items to loop over and the item iteration itself.
As I looked to split out the single component into several components (search, list of items and an item) - I saw that I couldn't change reactive properties from within a child component.
So, how should I be filtering my list of items. Do I handle that by way of state mutation or by computed properties in the child component?
Previously I was doing
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)
}
Should my filters apply from within the search component or as a mutation within state?