我正在使用 vuejs 3,我想过滤产品。在第一阶段,我想将参数发送到 URL,为此我使用 vue router。 目前,我的过滤器仅向每个组的 URL 发送一个参数,但我想将第一组的所有参数附加到 URL,而从第二组我只想将一个参数推送到 URL(中型或大型)
当我选择红色和中等尺寸时,我的过滤器就像这样 localhost:8080/filter?color=red&size=medium
。
但是如果我选择两种颜色,它应该附加两种颜色,我的URL应该如下 localhost:8080/filter?color=red&color=blue&size=medium
或 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>
P粉4349968452024-03-29 10:50:27
您应该为这个应用程序创建数据,如下所示,urlParams
以便每次有人点击颜色或尺寸并推送到它时获取数据。
data() { return { colors: [{id:1, name: "red" }, {id:2, name: "blue" }], sizes: [{id:1, name: "medium" }, {id:2, name: "large" }], urlParams: [] }; },
还有一些方法:
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) }, []) } },
您编写颜色和尺寸循环的模板:
Multi Filter By Color
{{ item.name }}Multi Size
{{ item.sizes }}