Check the button if it matches or not - Vue 2.7

khp

Joined
Jan 26, 2023
Messages
1
Reaction score
0
Hello

I ran into a problem because I checked that the value If it matches, return the toggle switch as checked (true), otherwise return the toggle switch as false.

as attached image

But the button is duplicated. How should I fix it?

image >> https://sv1.picz.in.th/images/2023/01/25/LSpikk.png

This my code

<div class="col-12" v-for="sch in schedule_artist" :key="sch.sch_id">
....
<div v-for="b in follows" :key="b.follow_artist_Id">
<div v-if="b.sch_id == sch.sch_id">
<label class="switch ms-3" >
<input type="checkbox" @click="createSW(sch.sch_id)" checked>
<div class="slider round"></div>
</label>
</div>
</div>
<label class="switch ms-3" >
<input type="checkbox" @click="createSW(sch.sch_id)" checked>
<div class="slider round"></div>
</label>
</div>

My script
export default {
data() {
return {
schedule_artist: [],
follows: [],
};

....
},
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
It seems that the issue is that you have a nested v-for loop and a toggle switch within each iteration of the outer loop. This creates multiple instances of the toggle switch with the same data, leading to duplicated buttons.

To resolve this, you can move the toggle switch outside of the nested v-for loop and bind its checked property to a computed property that checks whether the current sch object in the outer v-for loop has a corresponding follow in the follows array. Here's a potential solution:

Code:
<template>
  <div class="col-12" v-for="sch in schedule_artist" :key="sch.sch_id">
    ....
    <label class="switch ms-3">
      <input type="checkbox" @click="createSW(sch.sch_id)" :checked="isChecked(sch)">
      <div class="slider round"></div>
    </label>
  </div>
</template>
<script>
export default {
  data() {
    return {
      schedule_artist: [],
      follows: [],
    };
  },
  computed: {
    isChecked(sch) {
      return this.follows.some(b => b.sch_id === sch.sch_id)
    },
  },
  methods: {
    createSW(sch_id) {
      // your logic for toggling the switch here
    },
  },
};
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top