How to Display Bootstrap4 Modal in VueJS without using Jquery

Is there a way to display a Bootstrap modal from a function in VueJS using vanilla JS? I am working on a project that only uses standard Bootstrap 4 and not BootstrapVue.

//component.vue

<template>
  <div>
    <button type="button" class="btn btn-primary">My Modal</button>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          ...
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  methods: {
    buttonClick() {
      // Need to display modal in here
      //$('#myModal').modal("show")
    }
  }
};
</script>

Answer №1

When exploring how to implement a bootstrap modal with jquery, you will notice that they apply a show class to the modal and switch the style of the modal from style="display: none" to style="display:block"

In addition, a div

<div class="modal-backdrop fade show"></div>
is appended to the body, creating a black overlay background behind the modal.

You can achieve this by coding something similar to the following:

<template>
  <div>
    <button type="button" class="btn btn-primary" @click="toggleModal">Open Modal</button>
    <div
      ref="modal"
      class="modal fade"
      :class="{show, 'd-block': active}"
      tabindex="-1"
      role="dialog"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Modal Title</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
              @click="toggleModal"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>Modal body text goes here.</p>
          </div>
        </div>
      </div>
    </div>
    <div v-if="active" class="modal-backdrop fade show"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      active: false,
      show: false
    };
  },
  methods: {
    /**
     * When the button in bootstrap modal is clicked,
     * the modal display property changes and a show class is added.
     * To achieve this effect, we display the modal backdrop and set the modal's display property to block.
     * Then, we add the show class to the modal using setTimeout after showing the modal backdrop and changing the display property
     * This helps in making the modal animation work smoothly
     */
    toggleModal() {
      const body = document.querySelector("body");
      this.active = !this.active;
      this.active
        ? body.classList.add("modal-open")
        : body.classList.remove("modal-open");
      setTimeout(() => (this.show = !this.show), 10);
    }
  }
};
</script>

Check out the codesandbox demo for reference

I hope this explanation proves helpful for you!

Answer №2

This is the code I used:

<template v-if="showDialog">
  <div class="modal show" style="display: block;">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">{{ title }}</h5>
        </div>
        <div class="modal-body">
          <p> some stuff here </p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" type="submit"
            @click="emitSearch">
            Search
          </button>
          <button class="btn btn-secondary" type="button"
            @click="$emit ('close')">
            Cancel
          </button>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-backdrop show"></div>
</template>

I provided showDialog as a prop, but it might be better suited within data()

Answer №3

One issue we are facing is that the backdrop feature has stopped working as expected. Ideally, when clicking outside the modal, it should close automatically but currently, this functionality is not working. A more effective approach would be to implement a standard HTML dialog for better user experience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

granting authorization to modify content post channel establishment in discord using discord.js

I am encountering an issue with granting the message.author and staff permission to view the channel right after its creation. The problem arises when the channel's parent (category) is changed, causing it to synchronize with the permissions of the pa ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

New feature in Bootstrap 4 beta allows carousel arrows to be positioned outside of the

I created a text-based carousel using Bootstrap 4 beta. Is it possible to move the arrows off of the slider area and position them outside of it? I have tried searching on Google and in other forums, but I couldn't find a solution. The issue is that s ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

Changing the default download directory in Selenium using JavaScript

How can I use JavaScript to change the default download directory? I have a list of folders and one is named "C:\Study\Selenium". How do I update the location for downloaded files to this specific path in my code? chromeOptions.setUserPreference ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

What is the best method for gracefully opening external links in a reusable new tab?

Here is the progress I have made so far: <script> var win; function OpenInNewTab(url ) { // var win; if (win) { win.close(); } win =window.open(url, 'myWin'); win.focus(); } </script> My links are structured like ...

Is there a way to programmatically generate a component instance in Vue 3?

I am facing an issue with creating a vue 3 component instance programmatically within a directive. The error message 'tooltip is not a constructor' keeps popping up. Below is the relevant segment of my directive code: import tooltip from ' ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

Using Vue to Send Component Data to the User Interface

I am exploring Vue and trying to create a website with a Facebook login feature. I have a Facebook login component that is functioning properly, but I am struggling to make the acquired fbid and fbname available outside of the component in my Vues. I under ...

How can I load a URL without causing a page refresh?

While searching around, I stumbled upon this HTML 5 code snippet: window.history.pushState("object or string", "Title", "/new-url"); I started thinking: how can this be implemented? Is there a way to utilize this code to change the URL to without needin ...

Challenges related to the placement of the speed dial in Vuetify are causing

I'm trying to incorporate the vuetify speed dial component into my app, but I'm encountering odd positioning issues. What I want is for the button to be clicked and then the additional options slide out to the left of it. The image above shows t ...

Exploring byte array manipulation in node.js and techniques for data processing

Currently, I am faced with the challenge of retrieving a full byte array from a socket and then inserting it into a BLOB database without formatting the data. This is necessary as I specifically need to maintain the structure of the byte array. Initially, ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Can README docs be prioritized to appear before all other stories in Storybook navigation?

Organizing my Storybook stories is important to me. I like to nest all my stories under a “Docs” header, with each component having a README mdx file followed by its stories. My preferred order is to always have the README appear first in the navigatio ...

Encountering issues with loading JavaScript file in Reactjs

I'm currently working with Reactjs (Nextjs) and I am in the process of integrating the home page (index.js). I have various JavaScript files located in the "public" folder and I'm unsure of where to place them. Should I include these files in "_a ...

Is it possible to create a popup window that remains fixed at the top edge of the screen but scrolls along with the rest of the page if

In an attempt to organize my thoughts, I am facing a challenge with a search page similar to Google. The search results trigger a popup window when hovering over an icon, located to the right of the search results. Here is what I am looking to achieve with ...

Enhancing Online Presence with Video Gallery Website Development

I'm in the process of creating a website and need help finalizing my video page. I envision a layout similar to this example: https://i.stack.imgur.com/hctui.gif The main feature should be a large video placeholder at the top, followed by several thu ...