Is it possible for numerous identical components to trigger the display of the identical modal on a single webpage?

I am currently utilizing Vue in my project and I have a component that displays a button. When this button is clicked, it triggers a modal to open which is also part of the same component. The functionality works as intended.

However, if there are multiple instances of this button on the page, the modal opens multiple times due to the nature of the implementation. While I understand the reasoning behind this behavior, it is not the desired outcome for my application.

Below you can find the code snippet:

<template>    
    <div>
        <button @click="$bvModal.show('edit-profile-modal')" class="btn btn-sm btn-secondary mt-3">Edit</button>

        <b-modal id="edit-profile-modal" ref="editProfileModal" :ok-only="true">
            <template #modal-title>
                Edit your profile
            </template>
            <div class="d-block text-center">
                
            </div>
        </b-modal>
    </div>
</template>

<script>
    export default {
        props: {
        },

        data() {
            return {};
        },

        mounted() {
        },

        computed: {
        },

        methods: {
        }
    }
</script>

I am looking for a way to make the modal unique so that it does not get duplicated when multiple buttons are clicked. The content of the modal will always remain consistent regardless of which button triggers it.

While similar questions on StackOverflow discuss tables with 'Edit' buttons spawning modals containing form elements, my scenario involves a static modal with unchanging content. I aim to create a reusable component that users can interact with to open this specific modal without duplicating its presence.

Thank you.

Answer №1

Although this may be an older issue, I came across it while playing around with Bootstrap Vue's Modals and wanted to share a different approach.

BvModal uses IDs to distinguish templates, displaying all matching templates with the same ID when the show function is activated. So, to solve this, we just need to ensure that the IDs are unique!

An interesting way to achieve this is by leveraging the unique id assigned by Vue to its components:

<template>    
<div>
    <button @click="$bvModal.show(`edit-profile-modal-${_uid}`)" class="btn btn-sm btn-secondary mt-3">Edit</button>

    <b-modal :id="`edit-profile-modal-${_uid}`" ref="editProfileModal" :ok-only="true">
        <template #modal-title>
            Edit your profile
        </template>
        <div class="d-block text-center">
            
        </div>
    </b-modal>
</div>

It's important to note that template literals are used for both the $bvModal.show function and the id attribute of b-modal. If you prefer, you can also use

"'edit-profile-modal-' + _uid"
.

By implementing this method, you can include multiple instances of the same component on a page without confusing BvModal about which modal corresponds to each component, eliminating the need to create a custom component.

Answer №2

In order to avoid duplicating the modal each time you use it in a template, it's important to have the modal in its own component. You can create a separate component for the modal and import it into App.vue just once. Then, you can easily toggle the modal using a Vuex state.

ModalComponent.vue

<b-modal>
...
</b-modal>

App.vue

<template>
  <div>
    ...
    <ModalComponent v-show="showModal" />
  </div>
</template>
computed: {
  showModal() {
    return this.$store.state.showModal;
  }
}

store.js

state: {
  showModal: false
},
mutations: {
  toggleModal(state, isShown) {
    state.showModal = isShown;
  }
}

Any component can now easily utilize the mutation to display the modal:

methods: {
  displayModal() {
    this.$store.commit('toggleModal', true);
  }
}

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

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

Having trouble receiving JSON/JSONP correctly

I've been exploring the world of APIs and I'm facing a roadblock right at the beginning. My goal is to extract data from the Fever Public API in order to retrieve a list of subscribed RSS feeds. The API appears to be straightforward - check it ou ...

Loading fonts in Nuxt.js production modeIn a production setting, making

While everything works perfectly during development with preload including fonts, images, and scripts, the issue arises when building for production. The fonts are not preloaded in the final build - everything is there except the fonts. render: { http ...

Json data integrated dropdown menu

I have successfully retrieved data from a Json array and displayed it in a dropdown list. However, I am facing an issue where I want to only show the name of the city instead of both the name and description. If I remove cities[i]['description'], ...

Interacting with an element within a jQuery dialog box created through a function click

I'm encountering an unusual issue with jQuery and Javascript across all browsers (IE, FF, Chrome). On my (asp.net) webpage, I have the following structure: A header with numerous dynamically generated buttons at PreRender A hidden div containing but ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Is it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Refreshing Templates in Angular with ui.router

Initially, I apologize for the lengthy question, but it is necessary. Regrettably... I have multiple templates and routing logic stored in separate files. Strangely, the template I wish to load (depending on the selected region) does not initially load it ...

Create a form in a React component that allows the user to input information

My challenge is to create a functionality where each time the add button is clicked, it should dynamically add an input field that I can save. It's similar to this example, but with inputs instead. The complexity arises from the fact that the inputs a ...

The email message generated by sendGrid is kept confidential

When attempting to send emails using Node.js with SendGrid, I am experiencing an issue where the email content is always hidden. Here is my node.js code: const msg = { to: 'example@example.com', from: 'sender@example.com', ...

Subdomain redirection issue with express-subdomain for localhost GET requests

In order to manage requests to specific subdomains, I am utilizing a package in express.js called express-subdomain. From my understanding, the subdomain constructor function requires an express router object that I pass from an exported router module. M ...

Current recommended method for updating innerHTML with properly formatted text?

My understanding is that using innerHTML on an element can be risky, as malicious users could potentially inject harmful content such as <script> tags. This question shows there are multiple alternative tags, some of which are non-standard. In my s ...

The Quirks of jQuery's .load() Method

On my website, I am incorporating a basic jQuery script to load content from one part of a webpage into the 'display container' on the same page. The content being loaded consists of multiple divs enclosed within an outer <div> that is hid ...

Eliminate the selected item at random

I'm looking for a way to remove the randomly picked item from my namepicker so that it doesn't appear twice. const Names = [ { name: 'Name1', id: 1 }, { name: 'Name2', id: 2 }, ] btnClick = () => { let ...

Despite seeming false, my Javascript if statement still evaluates to true

On my webpage, I have a button and a form. The intended functionality is for the button to display the form when clicked, and hide it when clicked again. The issue I'm facing is that no matter if the statement is true or false, the first if statement ...

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...

Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself. I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "ite ...

Filtering a collection in Firestore using the `where()` method for a context provider in Next.js

i encountered an issue: when using the useEffect function to retrieve my firestore documents, it works well. Currently, I am fetching all "profiles" documents (3 in total). However, I now want to only retrieve the documents where the field "workerProfile" ...