Home » vue » Bootstrap modal in a loop in vuejs 2.0

Bootstrap modal in a loop in vuejs 2.0

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to create image gallery in vue.js, but this is the first time with this framework for me. I’m using vue-bootstrap, but I don’t know how to use modal, which is showing one image, not every image from an array.

This is my code:

<template>
  <div id="app">
<img v-b-modal.modal1 v-for="image in images" :src="image.url">

<b-modal id="modal1" title="Bootstrap-Vue">
  <img v-for="image in images" :src="image.url">
</b-modal>

<script>
export default {
  name: 'app',
  data () {
    return {
      images: [
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
      {url: require('./assets/logo.png')},
     ]
    }
  }
}
</script>
Answers:

If you want to show only 1 image:

<div id="app">
  <img v-b-modal.modal1 v-for="image in images" :src="image.url" @click="activeImageUrl = image.url">

  <b-modal id="modal1" title="Bootstrap-Vue">
    <img :src="activeImageUrl">
  </b-modal>
</div>

var app = new Vue({
  el: '#app',
  data: {
    images: [
{url: 'http://via.placeholder.com/350x150'},
{url: 'http://via.placeholder.com/350x160'},
{url: 'http://via.placeholder.com/350x170'},
{url: 'http://via.placeholder.com/350x180'},
{url: 'http://via.placeholder.com/350x190'}
],
    activeImageUrl: null
  },

});

Demo: https://codepen.io/ittus/pen/MGzKJo?editors=1111

###

You can use this template:

<img v-for="image in images" :src="image.url" @click="showModal(image)">

<b-modal ref="modal1" title="Bootstrap-Vue">
  <img ref="modalImage">
</b-modal>

And this method:

export default {
  name: 'app',
  data () {
    return { ... }
  },
  methods: {
    showModal(image) {
      this.$refs.modalImage.src = image.url
      this.$refs.modal1.show()
    }
  }
}