passing parameters to the URL in Vue.js

Using Vue.js 3, I am working on filtering products. My goal is to send parameters to the URL for filtering and I am utilizing Vue Router for this purpose. At the moment, my filter only sends one parameter to the URL from each group. However, I aim to append all parameters to the URL from the first group, and from the second group, I want to include only one parameter (either medium or large).

Currently, my filter output looks like this

localhost:8080/filter?color=red&size=medium
when I select red color and medium size. In the scenario where I select two colors, both colors should be appended, resulting in the URL looking like this
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>

Answer №1

To properly configure data for this application, you need to use the urlParams variable to track every click on color or size and add it to the array.

data() {
    return {
      colors: [{id:1, name: "red" }, {id:2, name: "blue" }],
      sizes: [{id:1, name: "medium" }, {id:2, name: "large" }],
      urlParams: []
    };
  },

Additionally, include the following methods:

methods: {
    activateFilter(e) {
      // Check if the color or size already exists in urlParams.
      if(!this.urlParams.includes(e)){
        this.urlParams.push(e);
      }

      // Generate params for the 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}&`
        }
      }, '')

      // Adjust for URL format.
    },
    createArrName(arrs) {
      return arrs.reduce((contains, current) => {
        return contains.concat(current.name)
      }, []) 
    }
  },

Lastly, in the template section, use loops to display 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue.js 3 to communicate data to slots

I've been struggling with a problem for the past few days that I just can't seem to find a solution for. It's a situation where I want to pass properties to child components using without specifying the scope in the parent component. Here i ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Error with constructor argument in NestJS validator

I've been attempting to implement the nest validator following the example in the 'pipes' document (https://docs.nestjs.com/pipes) under the "Object schema validation" section. I'm specifically working with the Joi example, which is fun ...

Having trouble installing $ npm i mini-css-extract-plugin. Any ideas on what might be causing the issue?

There seems to be an error in my setup. I am using Visual Studio Code with gitBash. $ npm i mini-css-extract-plugin npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-p ...

Make Bootstrap Panel Full Width with Highcharts Data

I am currently working on displaying graphs using the Highcharts library on three televisions. All televisions have a FULL HD resolution of 1920 x 1080. I have one Bootstrap panel containing a graph in the panel-body. <div class="panel panel-blue"> ...

Dynamic <figcaption> that adjusts to different screen sizes with smooth animations

My first WordPress theme is almost complete and I'm excited to share it: The responsive image grid on the homepage is giving me some trouble. When I shrink the browser window, the images don't scale properly. The grid works fine without the JS ( ...

`amqplib - What is the current number of active consumers on the queue?`

Seeking insight on using the amqplib module for Node JS and RabbitMQ: 1) Is there a method to determine the number of subscribers on a queue? 2) What is the process for ensuring that each queue has only one consumer key? Appreciate any guidance! ...

MUI: The fontFamily property is not able to be overridden by nesting within the

My goal is to have different fonts for different parts of my application using theme nesting. Unfortunately, I discovered that theme nesting doesn't work when it comes to overriding fonts. In my App.js file: import React from "react"; impor ...

What is the process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

Is there a way to optimize downloading multiple identical images using html, css, jquery, etc.?

My chess board features 64 squares, each with a picture of a board piece on either a light or dark square. To ensure proper formatting, a Clear knight is placed on the board. The design utilizes a div element with a background image (representing light or ...

What is the best way to embed an HTML tag along with its attributes as a string within an element?

https://i.sstatic.net/EZSOX.png Is there a way to incorporate this specific HTML tag with its distinct colors into an element within a JSX environment? I attempted the following approach: const htmlTag = '<ifx-icon icon="calendar-16"> ...

React animation failing to render underline animation

After tinkering with the underline animation while scrolling down on Codepen using Javascript, I successfully implemented it. You can check out the working version on Codepen. This animation utilizes Intersection Observer and a generated svg for the underl ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

Button inside table cell not showing Bootstrap tooltip

I've implemented a feature where each row in a table has a button that triggers a pop-up modal when clicked. I want these buttons to display tooltips when hovered over and when focused. Below is an example of the HTML structure: <link hr ...

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

What is the best method for gracefully opening external links in a reusable new tab?

Here is the progress I have made so far: <script> var win; function OpenInNewTab(url ) { // var win; if (win) { win.close(); } win =window.open(url, 'myWin'); win.focus(); } </script> My links are structured like ...

The error message encountered is: "Property 'http' cannot be found on type 'VueConstructor<Vue>' when using Vue-Resource with TypeScript."

I have been tackling a Typescript issue in a Vue project that relies on vue-resource. Despite the project functioning properly, I am encountering a typescript compiler error. https://i.sstatic.net/RFT8B.png https://i.sstatic.net/A2MZm.png I have managed ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...