Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time.

The issue arises when the page refreshes after selecting an option, causing the dropdown to close. This means that the user has to repeatedly open the dropdown every time they want to choose another option.

I am looking for a solution that will keep the selected dropdown open even after refreshing the page, ensuring a seamless user experience.

The visibility of the dropdown is controlled by the this.show value. By setting it to true in the mounted() function, all dropdowns are displayed initially. However, I only want the previously open dropdown to remain open upon reloading the page.

Here is the code for the Dropdown component:

<template>
  <div
    v-on-click-outside="collapse"
    class="dropdown"
    :class="{ expanded: show, collapsed: !show}"
  >
    <div
      class="dropdown__info"
      @click="onClick()"
    >
      <span>
        {{ getFilterTitle() }}
      </span>
    </div>
    <transition name="expand">
      <div
        v-if="show"
        class="dropdown__options"
      >
        <template v-for="(option, m) in filteredOptions">
          <template v-else>
            <div
              :key="option.value"
              :class="{
                selected: isSelected(option)
              }"
              :show="m < 10"
              class="dropdown__options__item"
              :title="option.title"
              @click="onSelect(option)"
            >
                {{ option.label }}
            </div>
          </template>
        </template>
      </div>
    </transition>
  </div>
</template>

Below are the functions used in the Dropdown component:

data() {
    return {
        show: false
    };
},
methods: {
    onClick() {
        if (this.show) {
         this.collapse();
        } else {
         this.expand();
        }
    },
    expand() {
        this.show = true;
    },
    collapse() {
        if (!this.show) {
         return;
        }
        this.show = false;
    },
    onSelect(option) {
        const selectedIndex = this.selectedList.findIndex(
        (selectedOption) => option.value === selectedOption.value,
        );

        const clonedSelectedList = JSON.parse(JSON.stringify(this.selectedList));

        if (selectedIndex > -1) {
         clonedSelectedList.splice(selectedIndex, 1);
        } else {
         clonedSelectedList.push(option);
        }

        this.selectedList = [...clonedSelectedList];

        this.onChange({
         title: this.title,
         name: this.name,
         value: this.selectedList,
        });
    }
}

Is there a way to maintain the visibility of the dropdown after selection so that users can easily choose multiple options without having to reopen the dropdown each time?

Answer №1

If you need to maintain the dropdown state on page reload and have multiple dropdowns, consider using localStorage. This allows you to save the id of the open dropdown and its selected options.

You can store this information in JSON format as shown below:

[
  {
    id: "html_el_id",
    selected: [ 
      "option1", 
      "option2" 
    ]
  }
]

You will need to determine how to generate unique ids for each dropdown and then synchronize the state from localStorage with the component's state based on the id.

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

The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data ...

How to implement a modal popup in Vue.js using an anchor tag

As a newcomer to Vue.js, I'm facing an issue with creating a link in my navbar component that, when clicked, displays a modal component. I've noticed that the solutions I found are for buttons which use the data target attribute, but this isn&apo ...

Using a functional wrapper component to reset the modal field in Reactstrap upon closing and reopening

In the main component that displays a list of to-do tasks, we have the ability to add or edit existing tasks. To facilitate this functionality, a separate wrapper was created. import React, { useEffect, useState } from 'react'; import { Label ...

How to Access Static Method from Non-Static Method in TypeScript

Within my hierarchy, there is some static content present in all levels (for example, the _image). It would be ideal to access the corresponding _image without repeating code: Here's what I envision: class Actor { static _image; // Needs to be s ...

What is the best approach to identify duplicated objects within an array?

I have an array with a specific structure and I am looking to add non-duplicate objects to it. [ { applicationNumber: "2", id: "8cca5572-7dba-49de-971b-c81f77f221de", country: 23, totalPrice: 36 }, { applicationNumber: "3", id: "8cc ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...

setting up default child route for vue-router tabs

I'm currently working on setting up a homepage that features tabs with 2 lists, one of which should be open by default. My route configuration looks like this; I've simplified the names for clarity: let routes = [{ path: '/', ...

The UseEffect function ceases to function properly upon refreshing the website

I'm currently using ReactJS for a project. I have a form that is intended to serve as the configuration for another form. The structure of this specific form is as follows: const [startingDate, setStartingDate] = useState(); const [endingDate, set ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

What is the best way for library creators to indicate to VSCode which suggested "import" is the correct one?

As a library creator, I have noticed that VSCode often suggests incorrect imports to users. For instance, VSCode typically suggests the following import: import useTranslation from 'next-translate/lib/esm/useTranslation' However, the correct im ...

Providing dynamic string outputs depending on the current date using AngularJS

I set up an advent calendar that reveals a new question every day, but currently the questions aren't showing up. Here's the code I have: The controller located in app.js: .controller('textCtrl', function($http) { this.data = {}; ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

"Executing Javascript event onmouseUp without needing a click and hold

I've implemented an event listener for onMouseUp. I'm trying to distinguish between a quick click (short time duration) and an onMouseUp event that occurs after holding the mouse for more than one second OR with onMouseDown while moving the mous ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code: this.router.navigate(['/collections/'+this.name], {id: this.id}); ...

Should WordPress files be kept separate (php, css, and js) or combined into a single file?

Currently, I am updating my WordPress website with a goal of minimizing the number of plugins used. To achieve this, I prefer writing code only for essential functionalities. In order to optimize my work with php, css, and javascript files, I have been exp ...