major697
major697

Reputation: 1862

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 ?

Upvotes: 0

Views: 171

Answers (2)

Ahsan Sohail
Ahsan Sohail

Reputation: 21

The active variable is shared for each item in your resourceList, you need to create active identifier for each item in your list, one way to do it is to have active property of item of resourceList. Assuming you have active property in each item of resourceList, you can do the following.

<div v-for="item in resourceList" :key="item.id">
    <input :id="roomData.id" type="checkbox" @click="saveCheckbox(item)">
    <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>

And the saveCheckbox method

saveCheckbox(item){            
   item.active = !item.active
}

Upvotes: 2

Vucko
Vucko

Reputation: 20844

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>

Upvotes: 1

Related Questions