I am currently dealing with an array of objects that represent continents:
data() {
return {
continents: [
{
name: "South America",
countries: [
{
name: "Paraguay"
},
{
name: "Chile"
}
]
},
{
name: "North America",
countries: [
{
name: "Costa Rica"
},
{
name: "Mexico"
}
]
}
]
}
}
// There are a total of 6 continents and over 250 countries.
I am attempting to apply a filter using v-model
called 'filter' like this
computed: {
filtered() {
return this.continents.filter(continent => {
continent.countries = continent.countries.filter(country => {
return country.name.match(new RegExp(this.filter, 'i'));
});
return continent.countries.length;
});
}
}
To display the results, I use the v-for
directive in the following way:
<input v-model="filter" type="text">
<div v-for="continent in filtered" v-if="filtered.length" class="countries-group">
<h4>{{ continent.name }}</h4>
<ul class="country-list">
<li v-for="country in continent.countries" class="country-item">{{ country.name }}</li>
</ul>
</div>
The process is almost successful, however my computed property 'filtered' is altering the original data for countries. This causes issues when trying to delete characters from the filter applied through v-model
, as it does not revert back to the initial data due to the modifications made by the filter.