0
votes

I am trying to use bootstrap-vue modal inside loop, something like:

<b-list-group-item v-for="item in items" :key="item">
      <b-button v-b-modal.example-modal>{{ item }}</b-button>
      <b-modal id="example-modal">
        <p>{{ item }}</p>
      </b-modal>
    </b-list-group-item>
<script>
export default {
  data() {
    return {
      items: [1, 2, 3, 4, 5, 6, 7],
    };
  },
};
</script>

Here the problem is whenever i click on one button it opens 7 modals (everyone inside the loop). For instance, if I click on button contain 3, it open all modal 1 to 7. How can I only call the modal whichever is clicked.

For you convenience here is codesandbox link: https://codesandbox.io/s/naughty-knuth-4q82p?file=/src/components/HelloWorld.vue:264-396

note that I need to use the modal inside the loop, because i have to pass some data to modal related to the v-for. Thanks is advance !

1

1 Answers

1
votes

You can do this two ways, the one i would recommend is using a single <b-modal>, and instead assign the "clicked" item to a data property which can be used to display the information you want.

Single Modal Example

new Vue({
  el: "#app",
  data() {
    return {
      items: [1, 2, 3, 4, 5, 6, 7],
      selectedItem: null
    }
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.css" />
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>

<div id="app">
  <b-list-group-item v-for="item in items" :key="item">
    <b-button v-b-modal.example-modal @click="selectedItem = item">{{ item }}</b-button>
  </b-list-group-item>
  <b-modal id="example-modal">
    <p>{{ selectedItem }}</p>
  </b-modal>
</div>

The other way is quite simple, which uses multiple <b-modal>s which are generated in your v-for. You give each modal a unique ID, and then use that ID in the v-b-modal directive.

Multiple Modal Example

new Vue({
  el: "#app",
  data() {
    return {
      items: [1, 2, 3, 4, 5, 6, 7]
    }
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.css" />
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>

<div id="app">
  <b-list-group-item v-for="item in items" :key="item">
    <b-button v-b-modal:[`example-modal-${item}`]>{{ item }}</b-button>
    <b-modal :id="`example-modal-${item}`">
      <p>{{ item }}</p>
    </b-modal>
  </b-list-group-item>
</div>