Search code examples
vue.jsvuejs2bootstrap-modalbootstrap-vue

why b-modal is not invoked when created in Vue?


I wanted to invoke the b-modal whenever the component is created but its not happening. Yet on clicking the button, the modal is invoked. How can we fix this?

<template>
  <b-container>
    <button @click="$bvModal.show('modal1')">Show</button>
    <b-modal id="modal1" title="Loading" hide-footer no-close-on-backdrop>
      <p>Preparing the Application, Please wait</p>
    </b-modal>
  </b-container>
</template>

<script>
export default {
  data() {
    return {};
  },
  created() {
    this.showModal();
  },
  methods: {
    showModal() {
      this.$bvModal.show("modal1");
    },
  },
};
</script>

Solution

  • When you want to interact with the HTML element, it's better to use the mounted hook.

    According to the Vue Lifecycle diagram and the API documentation, in the mounted hook, the elements are already rendered (not guarantee for child elements), so that you can interact with them.

    Meanwhile, in the created hook, you have access only to the data.

    Vue Lifecycle

    In short, in your case, the mounted hook is the solution.