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

Having difficulty controlling the DOM within an AngularJS template

My website utilizes AngularJS templates, specifically a Single Page Application (SPA). Within one of the templates, I am utilizing a tab control from the AngularUI library named Ui-Tabset. During the rendering process, this control generates a ul element ...

Whenever I attempt to run 'npm run serve', I encounter a SyntaxError. The error message specifies: Unexpected token, expecting "," at line 45, character 2. Can someone help me figure out what I'm missing here?

Whenever I type in `npm run serve`, I encounter a SyntaxError. The error message reads: `Unexpected token, expected "," (45:2)` What mistake am I making? Currently, my project involves working with Pusher and Vue.js within Visual Studio Code. I found t ...

What is the best way to update typings.json and typing files?

Here is the structure of my typings.json: { "globalDependencies": { "aws-sdk": "registry:dt/aws-sdk#0.0.0+20160606153210" }, "dependencies": { "lodash": "registry:npm/lodash#4.0.0+20160416211519" } } Currently, I find it tedious to update ...

What is the method for obtaining the entire object as a response following a click?

I am working on a basic JavaScript snippet: var image = [{name: "Breakfast", age: 100, author: "Alice"},{name: "Dinner", age: 10, author: "Teddy"}]; function gallery(name, content) { this.name = name; this.c ...

Invoke the ng-click function within the ng-change function

Just starting out with angularjs and I have a question. I am currently using single select and I want to retrieve the value selected and based on that value, perform an action. For example, if the value is "DELETE" then I would like to trigger the ng-clic ...

Validating Names in Vue.js

I need to create a form input field for a person's name. How can I make sure that only alphabets are allowed and numbers are not permitted? <div> <input type="text" class="from-input" placeholder="Enter Your Name..." v-model="name" /> < ...

Issue with undefined object reference in Moment.js when making an ajax request

Currently, I am working on developing a straightforward booking calendar using Eonasdan's bootstrap-datetimepicker, which relies on the moment.js library. To incorporate localization, I have included the necessary file. My setup consists of linked pic ...

Creating a basic popup with jQuery: A step-by-step guide

Currently in the process of creating a webpage. Wondering how to create a popup window with an email label and text box when clicking on the mail div? ...

Drag and Drop File Upload with Angular 2

I'm currently working on incorporating a drag and drop upload feature for angular 2, similar to the one found at: Given that I am using angular 2, my preference is to utilize typescript as opposed to jquery. After some research, I came across a libra ...

Issue: Unable to use the b.replace function as it is not recognized (first time encountering this error)

I can't seem to figure out what I'm doing wrong. It feels like such a silly mistake, and I was hoping someone could lend a hand in solving it. Here is my controller - I'm utilizing ng-file-upload, where Upload is sourced from: .controller( ...

Creating a personalized scrollball feature within a fancybox

Within my fancybox, I have a section with images that require a scroll bar. I currently have a scroll bar in place, but I am interested in implementing an anti-scroll (custom scrollbar) instead. I came across one option at https://github.com/Automattic/an ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

Retrieving currentUser data using Vue.js, Vuex, Express, and MongoDB

I am currently working on creating a MEVN stack authentication page that displays information about the user who is logged in. After successfully logging in, the router redirects to Home.vue and passes the username as a prop. The onSubmit method in Login. ...

Updating a select menu with AJAX without the need for a <div> tag within the form

Utilizing an ajax call to dynamically update a select menu is a common practice. The ajax call fetches the options from a separate .php file and populates the select menu accordingly. Below is the code snippet for inserting the dynamic content using JavaS ...

Possible revision: "Dynamic property naming in TypeScript interface based on specified type"

The concept might seem complex, but here's the gist of it. I have a User interface that may or may not contain certain properties depending on where it is fetched from. For example, there are optional properties like role and client_details. export i ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

Is there a way to stop the page from scrolling once I reach the bottom of a specific div within it?

My webpage has multiple divs that share a similar structure: <div style="height:200px; overflow:auto;"> <div style="height:300px;"> <!--There is a lot of content here--> </div> </div> When the user hovers ove ...

Exploring JSON data to extract values

I am facing difficulty parsing a complex array of JSON, specifically extracting the values "1238630400000" and "16.10". I need to extract all values from this JSON but I am unsure how to do it. Here is the code I have attempted so far: for (var key in my ...

There seems to be a glitch preventing the Redis client from properly executing

Having some trouble with my Redis implementation in Node.js. Despite using async/await as recommended in the docs, I'm only seeing 'console log 1' being logged. Any ideas on what might be causing this issue? Any help or suggestions would be ...