Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by clicking on a card - regardless of which card I click, the modal always shows the same values (from the first project). Here is a snippet of my code:

App.vue

<template>
  <div>
    <Navbar />
    <Projects />
  </div>
</template>
 
<script>
import Navbar from "./components/Navbar.vue";
import Projects from "./components/projects/Projects.vue";
 
export default {
  name: "App",
  components: { Navbar, Projects },
};
</script>

Projects.vue

<template>
  <div class="projects bg-light" id="projects_title">
    <h1>Projects</h1>
    <div class="projects_cards">
      <div v-for="project in projects" class="single_project" :key="project.id">
        <SingleProject :project="project"/>
          <Modal :project="project" />
      </div>
    </div>
  </div>
</template>
 
<script>
import SingleProject from "./SingleProject.vue";
import Modal from "../Modal.vue";
export default {
  data() {{
    return {
      projects: [
        {
          id: "1",
          number: "III",
          title:
            "Title 4",
        },
        {
          id: "2",
          number: "IV",
          title: "Title 4",
        },
      ],
    };
  }},
  components: {{
    SingleProject,
    Modal,
  }},
};
</script>

SingleProject.vue

<template>
  <div class="card mx-2" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">  {‌{project.number}} </h5>
    <h6 class="card-subtitle mb-2 text-muted">{‌{project.title}}</h6>
    <p class="card-text">Some quick example text</p>
    <a class="card-link" data-toggle="modal" data-target="#exampleModal">Project Card</a>
  </div>
</div>
</template>
 
<script>
export default {{
  props: {{project : {{
    type: Object
  }}}},
}}
</script>

Modal.vue

<template>
  <div>
    <div
      class="modal fade"
      id="exampleModal"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">{‌{project.id}}</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            {‌{project.title}}
          </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>
  </div>
</template>
 
<script>
export default {{
  props: {{
    project: {{
      type: Object,
    }},
  }},
}};
</script>

The props seem to be correctly set up. https://i.sstatic.net/Hmhgy.png

Answer №1

The issue I am facing is with this particular line:

<a class="card-link" data-toggle="modal" data-target="#exampleModal">Project Card</a>

The problem lies in the fact that the data-target triggers #exampleModal, which is an id shared by all modals. This leads to unexpected behavior.

To resolve this, there are different approaches you can take. One suggestion is to use the @click event instead, although this would require significant refactoring.

A quick fix could involve modifying the code as follows:

In Modal.vue:

:id="'exampleModal-' + project.id"

In Single Project.vue:

<a class="card-link" data-toggle="modal" :data-target="'#exampleModal-' + project.id">Project Card</a>

Make sure to update all ids with the formatted value for consistency.

I hope this solution works for you. Let me know how it goes and best of luck!

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

Removing a specific MySQL row using HTML in collaboration with Node.js

I've been working on a feature to allow users to delete specific rows from a table. Each row has a "Delete" link at the end, but when I click it, nothing happens. There are no errors displayed, and the console shows that 0 row(s) have been updated, ye ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 differ ...

Reactjs slider causes unexpected useState behavior

I created an autoplay Slider with three cards using the useEffect hook. However, the manual "previous" and "forward" buttons are not functioning correctly. The useState function is not updating values as expected, leading to unexpected changes in state. ...

Challenges arise in the grid system when implementing Material UI

Hey there, I've been trying to create card sets using material UI. I have organized the data from a JavaScript object, but unfortunately, the output is not what I expected. Below is the code I am currently using: const CardFeatures = () => { ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

What is the process for activating source maps in Webpack?

I am trying to incorporate source maps in my webpack.config.js file. However, the existing webpack configuration in the open-source project I am working on seems unfamiliar to me. webpack.config.js // This entry point webpack config dynamically switches ...

Issue with Laravel InertiaJS failing to render the head section

I am working on customizing the header for each page using Laravel inertia: <title inertia>Custom title...</title> <meta name="description" content="Custom page..." /> When creating a vue page: import { Head } from & ...

Is it possible to monitor and keep a record of every modification made to an HTML element?

Can anyone suggest an effective method to monitor changes made to an HTML element? I attempted to utilize JavaScript with jQuery but was unsuccessful. $('div.formSubmitButton input[type="submit"]').change(function(event){ alert( ...

What steps do I need to take to run my Angular project locally using globally installed npm packages?

I'm interested in maintaining all my packages globally, similar to how node package itself operates. For instance, if I have a package named "Highcharts" listed in my package.json file, I prefer to install it globally instead of creating a local node_ ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

The webpage fails to return to its original position after the script has been executed

My website has a sticky div that stays at the top when scrolling down, but does not return to its original position when scrolling back up. Check out this example function fixDiv() { var $div = $("#navwrap"); if ($(window).scrollTop() > $div.data("top ...

Issue with AngularJS script halting when reaching factory function that returns a promise

I have been working on a beginner project that is essentially a simple task manager (similar to those todo list projects). I created a user login page for this project and here is how it functions. There are two functions, siteLogin() for logging in, and ...

The reason behind the delay in discord.js interactions caused by the "foreach" method

I'm just starting out with JavaScript programming and I have a Discord bot where one of the commands is supposed to silence everyone in a call. However, I noticed that the command first silences five users, creates a pause, and then proceeds to silenc ...

The issue persists with `getServerSideProps` as it fails to retrieve data even when executed within the

Hey there! I'm currently facing an issue with fetching data in my Next.js app using getServerSideProps. The data is not being retrieved as expected, and I'm getting either an empty object or undefined in the console. I've tried various Next. ...

steps for incorporating AngularJS code into a bootstrap modal within an asp.net core mvc application

I am encountering an issue with using AngularJS code inside a Bootstrap modal. I am loading the modal using jQuery code, and after loading it, I want to utilize Angular JS code to fetch and insert data. The Angular code works perfectly fine in a separate v ...

Having trouble retrieving information from the server using ajax, javascript, jquery, and php

I am currently facing an issue with sending data retrieved from a jQuery call and attempting to save it to a server file using PHP. function getSVG(){ svghead = svghead + $('#test').html(); $.ajax({ type:"POST", da ...

What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element However, when I try to implement it in the code below, the background color ends up being transparent: { modules.map((module, index) => ( <div className='carou ...