Home > front end >  Several dropdowns in one component
Several dropdowns in one component

Time:07-23

I have several dropdowns menu in one component.

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

vue:

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

I feel like i need to use index, but still doesn't work for me. What i miss?

CodePudding user response:

You can save index in isOpen and then check it in template:

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 >
    <button @click="showInfo(index)">show</button>
    <div v-show="isOpen === index">{{ item.content }}</div>
  </div>
</div>
</div>

CodePudding user response:

You can achieve this in a very simple manner by just playing around with the itemIndex variable.

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  v-for="(item, index) in items" :key="index">
      <a @click="itemIndex = itemIndex ? null : index">{{ item.name }}</a>
        <div  v-if="itemIndex === index">
          <a href="" v-for="(option, i) in item.options" :key="i">{{ option }}</a>
        </div>
      </li>  
    </ul>
  </nav>
</div>

  • Related