'vue js push parameter to URL
I am using vuejs 3 and I want to filter the products. In the first stage I want to send parameters to URL and I am using vue router for this. Currently, my filter only send one params to URL from each group but I want to append all params to url from first group and from second group I want to push only one params to URL(either medium or large)
my filter is like this localhost:8080/filter?color=red&size=medium when I select red color and medium size.
But if I select two colours, it should append both colours and my URL should be as below localhost:8080/filter?color=red&color=blue&size=medium or localhost:8080/filter?color=red&color=blue&size=large
<template>
<div class="products">
<div class="multi_filters">
<h1>Multi Filter By Color</h1>
<a href="#" @click.prevent="activateFilter('color','red')">Red color</a>
<a href="#" @click.prevent="activateFilter('color','blue')">Blue color</a>
</div>
<div class="single_filter">
<h1>Multi Size</h1>
<a href="#" @click.prevent="activateFilter('size','medium')">Medium</a>
<a href="#" @click.prevent="activateFilter('size','large')">Large</a>
</div>
</div>
</template>
<script>
export default {
data() {
return {
filters:{},
selectedFilters:{}
}
},
methods:{
activateFilter(key,value){
this.selectedFilters = Object.assign({},this.selectedFilters,{[key]:value})
console.log(this.selectedFilters)
this.$router.replace({
query: {
...this.selectedFilters
}
})
}
}
}
</script>
Solution 1:[1]
You should create data for this app like this , urlParams to get everytime someone click on color or size and push to it.
data() {
return {
colors: [{id:1, name: "red" }, {id:2, name: "blue" }],
sizes: [{id:1, name: "medium" }, {id:2, name: "large" }],
urlParams: []
};
},
And some method:
methods: {
activateFilter(e) {
//get color or size with condition not exist.
if(!this.urlParams.includes(e)){
this.urlParams.push(e);
}
//create params url
const urlParam = this.urlParams.reduce((contains, current) => {
if(this.createArrName(this.colors).indexOf(current) > -1){
return contains += `color=${current}&`
}else{
return contains += `size=${current}&`
}
}, '')
//adapt to url
},
createArrName(arrs) {
return arrs.reduce((contains, current) => {
return contains.concat(current.name)
}, [])
}
},
And template you write loops of colors and sizes:
<template>
<div class="products">
<div class="multi_filters">
<h1>Multi Filter By Color</h1>
<a v-for="item in colors" :key="item.id" @click.prevent="activateFilter(item.name)">
{{ item.name }}
</a>
</div>
<div class="single_filter">
<h1>Multi Size</h1>
<a v-for="item in colors" :key="item.id" @click.prevent="activateFilter(item.name)">
{{ item.sizes }}
</a>
</div>
</div>
</template>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
