我正在使用 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 }}