Answer the question
In order to leave comments, you need to log in
vue-router. What magic is happening?
Hello! I ask for help from vue-router or nuxt experts. There is one online store on vue. There is a header with categories of pages, let there be category1, category2, category3. The transition to the category occurs with the help of vue-router - at the moment of transition, the category slug is written to the params and, depending on the slug, the page content is formed. Some pages have product filters - pictures wrapped in nuxt-link. It is assumed that when the user clicks on the filter, I will call the setRouter function, which, depending on the number of active filters, will either write the filter slug into params if one filter is active; or in query if there are several of them; or return the url of the category if there is no active filter. I suppose to store active filters in activeFilterIds
<ul class="filter-list">
<li class="filter-list__item" v-for="(filter, index) in filters" :key="index">
<nuxt-link
:to="setRoute(filter)"
class="filter-list__link">
<div class="filter-list__box" @click="handleClickFilter(filter.slug)">
<img
v-if="activeFilterIds && activeFilterIds.includes(filter.slug)"
class="filter-list__img"
:src="`${filter.iconActive}`"
:alt="filter.title" />
<img
v-else
class="filter-list__img"
:src="`${filter.iconDefault}`"
:alt="filter.title" />
</div>
<span class="filter-list__title">{{ filter.title }}</span>
</nuxt-link>
</li>
</ul>
data() {
return {
activeFilterIds: this.$route.params.filter || this.$route.query.filters || []
}
},
methods: {
setRoute(filter) {
let url;
if(this.activeFilterIds.length === 0) {
url = `/${this.$route.params.category}`;
}
if(this.activeFilterIds.length === 1) {
url = `/${this.$route.params.category}/${this.activeFilterIds[0]}`
}
if(this.activeFilterIds.length > 1) {
url = {query: {filters: this.activeFilterIds}}
}
return url
},
handleClickFilter(filter) {
if(this.activeFilterIds) {
const index = this.activeFilterIds.findIndex(item => item === filter);
if(index !== -1) {
this.activeFilterIds.splice(index, 1);
} else {
this.activeFilterIds.push(filter);
}
} else {
this.activeFilterIds.push(filter);
}
}
}
Answer the question
In order to leave comments, you need to log in
It is supposed that when the user clicks on the filter, I will call the setRouter function...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question