Currently, I have a feature on my website where users can filter articles based on their category. When the user selects the "ideas" filter, it creates a new array called "ideasFiltered" and stores it in the "filteredArticles" state. This works perfectly when navigating back to the page using the browser's back button. However, if a user goes to another page on the website and then returns to the news page, the previously filtered list is still displayed. Is there a way to only save this filtered data when returning using the back button or from an article page?
Below is my Vuex store setup:
const store = new Vuex.Store({
state: {
filteredArticles: this.articles
},
mutations: {
setFilteredList (state, value) {
state.filteredArticles = value
}
},
plugins: [
createPersistedState()
]
})
Computed property for filtering:
computed: {
filteredArticles () {
return store.state.filteredArticles
}
}
Here's an example of the script that runs when the "ideas" filter is selected:
ideas: function ideas() {
this.$store.commit('setFilteredList', articles) **// resetting to the full list before filtering**
var ideasFiltered = this.filteredArticles.filter(function(post) {
return post.category === 'Ideas';
});
this.filteredCategory = 'ideas'; **// used to update the URL with the category**
this.$store.commit('setFilteredList', ideasFiltered) **// committing the filtered list to the store**
}
Lastly, here is the HTML structure for displaying the articles:
<div class="news-article-list">
<ul>
<li v-for="(article, index) in filteredArticles" :key="index">
<a :href="article.url">
<img :src="article.featureImg" v-if="article.featureImg" alt="Article Feature Image" />
<h2 class="news-title">{{ article.title }}</h2>
<p class="news-date">{{ article.date }}</p>
<p class="short-desc">{{ article.shortDesc }}...</p>
</a>
<router-link class="read-more" :to="article.url">Read More</router-link>
</li>
</ul>
</div>
If further explanation is needed, feel free to ask. I want to ensure that all articles are displayed when navigating to different pages but retain the filtered list when going back from an article.
Thank you in advance!