Multiple selection menus within a single module

I am working on a component with multiple dropdown menus.

<div v-for="(item, index) in items" :key="index"> 
  <div class="dropdown">
    <button @click="showInfo(index)"></button>
    <div v-show="isOpen">{{ item.content }}</div>
  </div>
</div>

Vue:

showInfo(index) {
    this.isOpen = !this.isOpen;
},

I believe I need to utilize the index, but it's not functioning as expected. What could be causing this issue?

Answer №1

If you store the index value in the isOpen variable, you can easily check it in the template like this:

const app = Vue.createApp({
  data() {
    return {
      items: [{content: 1}, {content: 2}, {content: 3}],
      isOpen: null
    };
  },
  methods: {
    showInfo(index) {
      this.isOpen = this.isOpen === index ? null : index;
    },
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(item, index) in items" :key="index"> 
  <div class="dropdown">
    <button @click="showInfo(index)">show</button>
    <div v-show="isOpen === index">{{ item.content }}</div>
  </div>
</div>
</div>

Answer №2

To easily achieve this, simply manipulate the itemIndex variable for the desired effect.

See it in action with a Live Demo :

new Vue({
  el: '#app',
  data: {
    items: [{
        name: 'Dropdown Menu 1',
      options: ['Option 1', 'Option 2', 'Option 3']
    }, {
        name: 'Dropdown Menu 2',
      options: ['Option 4', 'Option 5', 'Option 6']
    }],
    itemIndex: null
  }
})
ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  background-color: #F2C777;
}
li a {
  display: block;
  padding: 10px;
  text-align: center;
  color: #7C785B;
}
li a:hover {
  background-color: #EC8C65;
}   
li {
  display: inline-block;
} 

.droplinks {
  position: absolute;
  background-color: #F2D299;
  min-width: 140px;
  display: block;
}

.droplinks a {
  padding: 10px;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <nav>
    <ul>
      <li class="dropbutton" v-for="(item, index) in items" :key="index">
      <a @click="itemIndex = itemIndex ? null : index">{{ item.name }}</a>
        <div class="droplinks" v-if="itemIndex === index">
          <a href="" v-for="(option, i) in item.options" :key="i">{{ option }}</a>
        </div>
      </li>  
    </ul>
  </nav>
</div>

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

Achieve the appearance of a galloping horse using JQuery

I am looking for a way to create the illusion of a horse running by displaying a sequence of images quickly. Each image in my folder shows the horse in motion, and I want to make it appear as if the horse is actually moving. Can anyone recommend a librar ...

HTML not being able to execute Javascript when using an SSL connection

While serving HTML via Jenkins HTTPS with an invalid security certificate, the following code is included: <!DOCTYPE html> <html> <head> <script type="text/javascript">alert(1);</script> <script type="text/javascri ...

Is it possible for you to generate an array containing only one element?

I've encountered an issue with my code. It functions correctly when the JSON data for "Customers" is in array form. However, if there is only one customer present, the code erroneously creates 11 table columns (corresponding to the number of keys in t ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

How can communication be established between JavaScript and a .NET app?

I've been developing a help system using HTML, and I want to include clickable links that can trigger commands in a .NET application (such as guiding users through tutorials or workflows). I have explored the TCard() method for HTML help, but it seems ...

How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider: inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2} In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as t ...

Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

Activate the element only when all input fields are completed. This function can be used repeatedly

I am working on developing a versatile function that will iterate through all input fields. If any of these fields are empty, I want to trigger the toggling of a class name (disabled) on another element (such as an anchor or button). Currently, the functi ...

Accessing a parent class constructor object in NodeJS from the Child Class

I'm currently working on creating a Controller Class that will handle the initialization of all my routes using ExpressJS. Below is a simple example of what I have so far: class Test extends Controller { constructor(App) { const Routes = [ ...

If the condition is true, apply a class with ng-class when ng-click is triggered

I am facing a situation similar to toggling where I am adding the class col-xs-6 to divide the page into two views. Initially, when I click, I set a variable value as true and in ng-class, I check for a condition to append the col-xs-6 class. Below is the ...

Submit form in a new tab and refresh the current page

It seems like my mind is hitting a roadblock, I'm having trouble finding a better solution for this particular issue: I need to send a form via POST method (with data handling on the server) and have it open in a new tab with a custom URL containing ...

After retrieving a value from attr(), the object does not have the 'split' method available

I need to implement the split method on a variable fetched using attr. This is the code snippet I am attempting: $(document).ready(function() { $('.some_divs').each(function() { var id = $(this).attr('id'); var ida = ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

Issue: EACCES error - permission denied in Vue Cli generated project

Whenever I try to create a project using the vue create command, I keep getting an error saying "Error: EACCES: permission denied" for each change I make. I installed Vue Cli by running the sudo npm install -g @vue/cli command. Here are my system details: ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Ways to modify client socket from JavaScript to PHP

Looking for a way to convert a client socket from JavaScript to PHP in order to receive data from the server socket? Check out the PHP socket Bloatless library here. This is an example of the Client Javascript code: <script> // connect to chat appl ...

Clicking on an embedded YouTube video will automatically redirect you to the video's

Hey there, I've added an embedded video to my website and I'm wondering if it's possible to redirect users to a new site when they click the play button? Thanks in advance! ...