0

I have a v-if inside a v-for. I want to have a button inside that can toggle content on and off but a click on one instance will open all instances on the page. How I can I only open and close the particular div that I click.

Here is the code.

<div v-for="user_leav in user_leave_filtered" v-bind:key="user_leav.id">
  <div class="container">
    <div v-if="user_leav.note" v-on:click="showNote = !showNote">
      <h4>Note</h4>
    </div>
    <div class="note" v-if="showNote">
      <p>{{ user_leav.note }} </p>
    </div>
  </div>
</div>

Thanks

SamohtVII
  • 137
  • 2
  • 12

2 Answers2

2

You could add showNote inside the user_leav

<div v-for="user_leav in user_leave_filtered" v-bind:key="user_leav.id">
  <div class="container">
    <div v-if="user_leav.note" v-on:click="user_leav.showNote = !user_leav.showNote">
      <h4>Note</h4>
    </div>
    <div class="note" v-if="user_leav.showNote">
      <p>{{ user_leav.note }} </p>
    </div>
  </div>
</div>

Or else you would have to define showNote as an array

<div v-for="(user_leav, index ) in user_leave_filtered" v-bind:key="user_leav.id">
  <div class="container">
    <div v-if="user_leav.note" v-on:click="showNote[index] = !showNote[index]">
      <h4>Note</h4>
    </div>
    <div class="note" v-if="showNote[index]">
      <p>{{ user_leav.note }} </p>
    </div>
  </div>
</div>

For the second solution, you will have to make a watcher to "reinitialize" the showNote array, each time the filters change.

watch: {
  user_leave_filitered(newVal) {
    // Requires polyfill
    this.showNote = new Array(newVal.length).fill(false)
    // Or
    this.showNote = new Array(newVal.length);
    for( note of this.showNote ) {
      note = false;
    }
  }
}

Keep in mind: Array.prototype.fill is not supported in Edge, therefore would need a polyfill.

Crackers
  • 1,097
  • 6
  • 14
1

Use functions to manipulate the data and check if the id has been clicked.

<div v-for="user_leav in user_leave_filtered" v-bind:key="user_leav.id">
  <div class="container">
    <div v-if="user_leav.note" v-on:click="toggle(user_leav)">
      <h4>Note</h4>
    </div>
    <div class="note" v-if="checkNote(user_leav.id)">
      <p>{{ user_leav.note }} </p>
    </div>
  </div>
</div>

And then add add and remove items from an array and check against that array.

data () {
    return {
      showNote: []
    }
  },   
methods: {
  toggle: function (userLeavePassed) {
    if (this.showNote.includes(userLeavePassed.id)) {
      var index = this.showNote.indexOf(userLeavePassed.id)
      if (index > -1) {
        this.showNote.splice(index, 1)
      }
    } else {
      this.showNote.push(userLeavePassed.id)
    }
  },
  checkNote: function(notePassed) {
    if (this.showNote.includes(notePassed)) {
      return true
    } else {
      return false
    }
  }
}
MomasVII
  • 4,641
  • 5
  • 35
  • 52