Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

v-for loop and use of key attribute

Could not frame the title more relevantly , sorry for that....

  • I have an [ ] in my data property which gets filled with items with a call from external API

  • I loop through the [ ] using v-for on the main div in my template and populate the page

  • there is a toggleable div in every main div which is hidden by default and is toggleable whether to display or not

here's the code

<template>

  <div>    
      // MAIN DIV
      <div v-for="(item, index) in myArray :key="index"> 
          //populate the elements using revelevant data
        <button @click="toggleDiv"">show/hide</button>

        //togglelable div
           <div v-if="displayDiv">
            //some data
        </div>
      </div>
  </div>
</template>

<script>
    export default{
        data(){
            return{
                myArray: [],
                displayDiv: false
            }
        },
        methods: {
            toggleDiv(){
                this.displayDiv = !this.displayDiv;
            }
        }

    }
</script> 

So here's my problem

  • when i click the button in a particular div to show the hidden div, all the hidden divs of the rest all divs are also getting displayed

  • how do i restrict this from happening so that only respective hidden div is toggled when respective button of that div is clicked

  • should I use key attribute to let vue distinguish the divs or i should use any logic

like image 863
Vamsi Krishna Avatar asked Apr 18 '17 11:04

Vamsi Krishna


1 Answers

You must leave name of key and value like so, don't rename it.

<div v-for="(value, key, index) in Your-object">
  {{ index }}. {{ key }}: {{ value }}
</div>
like image 61
Emad Adly Avatar answered Sep 28 '22 11:09

Emad Adly