Skip to content
Advertisement

With Vue.js, How to use a modal component inside v-for loop?

i made v-for loop cards with vue-Bootstrap.

in state, there are dummy. like this.

 myTeams: [
{name: "T1", img: "https://placekitten.com/300/300" , nickname: "", followers: 14565, category: "lol"},
{name: "ManU", img: "https://placekitten.com/300/300" , nickname: "", followers: 1234, category: "football"},
{name: "Chelsea", img: "https://placekitten.com/300/300" , nickname: "", followers: 76567, category: "baseaball"},

],

and here is my vue.js code

<template>
  <div>
    <br>
    <b-card-group columns deck>
        <br>
        <br>
        <b-card 
          v-b-modal.modal-1
          v-for="(team, idx) in myteams"
          :key = "idx"
          :team="team"
          :src = "team.img"
          border-variant="success"
          tag="article"
          style="max-width: 15rem;"
          class="mb-2"
        >
          <b-container>              
            <b-avatar 
            :src="team.img" 
            size="6rem"
            class="d-flex"
            >
            </b-avatar>
            <br>
            <b-card-title>
            <div v-if="team.nickname.length === 0">{{ team.name }}</div>
            <div v-else>{{ team.nickname }}</div>
            </b-card-title>
              <b-card-text>
                {{ team.followers }} people like this team.
              </b-card-text>
            <b-button pill variant="danger" size="sm">delete</b-button>
      
          </b-container>
          <b-modal id="modal-1" :title="team.name">
            <p class="my-4">{{team}}</p>
          </b-modal>
        </b-card>       
    </b-card-group>
  </div>
</template>

and js

<script>
import { mapState } from 'vuex'

export default {
  name: 'MyMyTeam',
  computed: {
   ...mapState({
     myteams: 'myTeams'
   })
  },

}

i just wanna each card has its own modal ex) when i click ManU card, just one modal will be activated and it has ManU data but in my code, when i clicked a card, 3 modals was activated…. T1, ManU, Chelsea

how can i resole it?

Advertisement

Answer

Try to add ‘id’ in your Array, and put the ID of Array as a Key.

v-for="team in myteams"
:key="team.id"

Or, change the key of loop :key=”team.name” if you won’t add ‘id’

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement