Search code examples
vue.jsrenderv-for

Vue v-for click not show correcly element


for` to show data from database:

<div v-for="item in resourceList" :key="item.id">
    <input :id="roomData.id" type="checkbox" @click="saveCheckbox">
    <label :for="roomData.id">{{ item.question }}</label>

        //calendar
        <span v-if="active">
            <datepicker v-model="date"></datepicker>
        </span>
        <span v-else id="disableCalendar">Not show calendar</span>
</div>

I have problem with function click. For example on page v-for show 10 elements. In each element there will be a button to click @click="saveCheckbox".

Function in methods:

saveCheckbox(e){            
    if(e.target.checked) {
        this.active = true;
    } else {
        this.active = false;
    }
}

In data I have:

active = false;

Now when user click in for example first element button, the calendar will appear in EACH element. How I can show calendar ONLY in element which user clicked ?


Solution

  • You need to store the value for each item in the loop. With this.active = true you have only one state which you use for every item in the loop.

    Example:

    new Vue({
      el: "#app",
      data: {
        isActive: [false, false, false, false]
      },
      methods: {
        toggleActive(index) {
          this.$set(this.isActive, index, !this.isActive[index])
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="(active, index) in isActive" :key="index">
        {{ active }} {{ index }}
        <button type="button" @click="toggleActive(index)">Toggle</button>
      </div>
    </div>