Categories
Vue Answers

How to pass data to modal with Bootstrap-vue?

Spread the love

To pass data to a modal using BootstrapVue, you can utilize Vue.js’s data binding capabilities.

There are multiple ways to achieve this, but a common approach is to use props to pass data from the parent component to the modal component.

For example:

Parent Component:

<template>
  <div>
    <!-- Button to open modal -->
    <b-button @click="openModal">Open Modal</b-button>

    <!-- Modal component -->
    <ModalComponent :data="modalData" @close="closeModal" />
  </div>
</template>

<script>
import ModalComponent from './ModalComponent.vue';

export default {
  components: {
    ModalComponent
  },
  data() {
    return {
      modalData: { /* Initial data for modal */ }
    };
  },
  methods: {
    openModal() {
      // Open the modal
      // Update modalData if necessary before opening
      this.$bvModal.show('myModal');
    },
    closeModal() {
      // Close the modal
      this.$bvModal.hide('myModal');
    }
  }
};
</script>

Modal Component (ModalComponent.vue):

<template>
  <b-modal id="myModal" @hidden="$emit('close')">
    <!-- Modal content -->
    <div>
      <h5>Modal Title</h5>
      <p>{{ data }}</p>
    </div>
  </b-modal>
</template>

<script>
export default {
  props: ['data']
};
</script>

In this example, the parent component (ParentComponent) contains a button to open the modal and a modal component (ModalComponent).

The ModalComponent is passed a prop named data, which can be any data you want to display in the modal.

When the button is clicked, the openModal method is called, which updates modalData if necessary and then shows the modal using BootstrapVue’s $bvModal.show() method.

When the modal is closed (either by clicking outside or by a close button), the closeModal method is called, which hides the modal using BootstrapVue’s $bvModal.hide() method.

This setup allows you to pass data from the parent component to the modal component and display it within the modal.

Adjust the data and logic as needed for your specific use case.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *