Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management.
In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iteration process itself.
However, when I attempted to divide the single component into multiple components (search, item list, and individual item), I noticed that I couldn't modify reactive properties from within a child component.
Now, I'm contemplating how to filter my list of items. Do I achieve this through state mutation or by using computed properties in the child component?
This was my previous approach:
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)
}
My dilemma now is whether the filtering should be done within the search component itself or as a mutation within the state?