Triggering a Vue.js modal with a button click

How can a button be used to display a modal in other components? Here are the example components:

info.vue

<template>
  <div class="container">
    <button class="btn btn-info" @click="showModal">show modal</button>
    <example-modal></example-modal>
  </div>
</template>

<script>
import exampleModal from './exampleModal.vue'
export default {
  methods: {
    showModal () {
      // how to show the modal
    }
  },
  components:{
    "example-modal":exampleModal
  }
}
</script>

exampleModal.vue

<template>
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            hihi
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
        </div>
    </div>
    </div>
</template>

How can the modal be shown from exampleModal.vue? Using "data-toggle" and "data-target" is one way to show the modal, like this:

<button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>

Is there another method to show the modal rather than using "data-toggle" and "data-target"? One option is utilizing the "showModal" method.

Answer №1

Your Bootstrap modal setup seems to be a classic one. To trigger the modal, make sure to include the data-toggle and data-target attributes like this:

<div id="app">
  <div class="container">
    <button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>
    <example-modal></example-modal>
  </div>
</div>

Edit

I misunderstood the question initially, so here's an updated answer.

If you want to open the modal using a custom method, you can target the element "#exampleModal" with refs and then trigger it using a Bootstrap method (Bootstrap Programmatic API)

<div id="app">
  <div class="container">
    <button class="btn btn-info" @click="showModal">show modal</button>
    <example-modal ref="modal"></example-modal>
  </div>
</div>
methods: {
  showModal() {
    let element = this.$refs.modal.$el
    $(element).modal('show')
  }
}

Check out this Fiddle example

Answer №2

If you're not using jQuery, one way to achieve the same functionality is by implementing a function within the "method:" block as shown below:

showEditModal(data){
  // <process your data>
  this.$root.$emit("bv::show::modal", "your-modal-id");
}

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

Using dojox gfx to enable a node to be draggable following retrieval of sgv data from a JSON source

I have a collection of shapes on a surface that I need to convert to JSON using the dojox.gfx.utils.toJson(surface) method. Once I have the JSON data, I then utilize dojox.gfx.utils.fromJson(surface, json) to append it back to the surface. However, I enco ...

Internet Explorer 8 is not compatible with jQuery fadeIn and fadeOut functions

Recently, I created a script that allows for fading in and out an error container. Surprisingly, it seems to work perfectly in Firefox and Chrome but unfortunately fails to function altogether in Internet Explorer 8. If you're interested, feel free t ...

Is it possible to automatically mute an HTML 5 video when closing the modal?

Is there a way to pause a video that plays in a modal and continues playing in the background when the modal is closed? I am using the Materialize library. <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!-- Compiled ...

Encountered an issue while attempting to connect MongoDB to Node.js

``const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description); .MongoServerSelectionError: connect ECONNREFUSED ::1:27017 const {MongoClient}=require('mongodb'); c ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...

The Three.js camera imported from Collada is unable to properly focus on an object within the scene

Having some trouble grasping the concept of Collada Animation in Three.js! I have an animation with a moving camera in 3Dsmax, and exported the scene into Collada. loader.load( ColladaName, function ( collada ) { model = collada.scene; model.upda ...

Getting a Stripe subscription securely and increasing it by 1 using Node.js

Recently, I delved into using Stripe for processing payments in node.js. My goal is to set up a payment system with the following structure: Initiate a workspace and establish a $10 per month Stripe subscription. Each new member joining the workspace wil ...

Manipulating element height in AngularJS

My goal is to utilize the bootstrap style for a fixed navigation bar at the top of the page. By using navbar-fixed-top, I can fix an element to the top. The visibility of #subnav will be determined by the value of showsubnav. <div id="backnav"> ...

Looping in REACT with state updates can cause the values to be overwritten

I'm encountering a problem with my function in React that updates the state. It fetches data from a URL in an array and creates a new item, but when trying to update another state array with this new object, it keeps overriding the first item each tim ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Finding the count of elements within an array collection using JavaScript

I have a number of arrays each containing various objects: arr1=[obj1, obj2, obj3, other1, other2] arr2=[obj1, obj2, other1] ...//additional arrays with different numbers of objects My objective is to calculate the total count of "obj" objects while disre ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

Is it possible to access a service within the config function or access a provider from inside a service?

Need help configuring angular bootstrap tooltip (uibTooltip) to be disabled on mobile devices with angular-bowser for device detection. One possible solution is: isMobile = _bowser.mobile $uibTooltipProvider.options = { trigger: isMobile ? "none" : "mous ...

Tips for importing a Multimaterial .dae file in three.js?

I am facing an issue while trying to load a model with multiple materials. I want to access the array of materials but my current approach is not working as expected. loader.load('./dae/tenis.DAE', function ( collada){ dae = collada.scene; ...

Identifying the moment a member receives a role using my Discord bot built with discord.js

I am currently working on detecting when a user is assigned a specific role on a server. Here is the code I have been using: // Require the required discord.js classes const { token } = require('./config.json'); // Create a new client instance ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

The inheritance caused this scope to be lost

Here is an illustration of code with two files and "classes". In the CRUD class, there is a problem with this.modelName when setting routes as it changes the context. The question arises on how to maintain the same scope within the CRUD where modelName is ...

Exploring the Process of Iterating Through a JSON Array in Angular

Within my angular application, I am utilizing an API to retrieve data regarding a chosen country. However, I am encountering difficulties in showcasing the "name" property from the languages section within the response data: [{ "name": "Colombia", ...

What is the best way to reach the parent controller's scope within a directive's controller?

In a scenario where I have a custom directive nested inside a parent div with a controller that sets a variable value to its scope, like this: html <div ng-controller="mainCtrl"> <p>{{data}}</p> <myDirective oncolour="green" ...