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.

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

Using dot notation for event handlers in Vue.Js is a handy technique

I am currently developing a Single Page Application (SPA) using Vue.js 3 and Bootstrap 5. On the main page, I have implemented the Bootstrap Offcanvas element with code that closely resembles the one provided in the documentation. The structure of the off ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

Utilizing the document.createDocumentFragment() method along with innerHTML for manipulating a Document Object Model (

I am currently in the process of creating a document fragment using the code below: let fullHTMLDocument = '<!doctype html> <html><head></head><body><h1>hello world</h1></body></html>'; let f ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Change from using fs.writeFileSync to fs.writeFile

I have a question about changing fs.writeFileSync to fs.writeFile const users = { "(user id)": { "balance": 28, "lastClaim": 1612012406047, "lastWork": 1612013463181, "workersCount": 1, ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

How can JavaScript be used to delete cache and cookies?

Looking for a solution to clear cache and cookies via JavaScript? I'm currently using Selenium for testing in Microsoft Edge, but the tests are running in the same session as the previous run. I need each test to run in a clean session every time. Unf ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

The Owl carousel's autoplay feature seems to be set at a fixed speed of 5

I've been attempting to adjust the autoplay speed on an owl carousel (specifically using owl carousel 1), but no matter what integer I add after autoplay:, it remains stuck at 5 seconds. The website, which is currently broken, suggests that adding a n ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

Unable to modify existing attributes in a sails.js model

I'm new to sails.js and I have a question about adding fields to an existing model in Sails.js. Here is the current model: module.exports = { attributes: { id: { columnName: 'id', type: 'integer&apos ...

"Efficient Ways to Manage Various File Types in React: xlsx, pptx, doc, docx

I am encountering an issue with downloading files in my React application. The API is functioning properly as confirmed using Postman, where different file formats such as xlsx, pptx, doc, docx, ppt and xls can be downloaded and opened successfully. Howev ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

Setting a default value in a multi-select dropdown using react-select

I have taken over management of my first React app, and I am facing a seemingly simple change that needs to be made. The modification involves an email signup page where users can select their interests from a multi-select dropdown menu. My task is to mak ...

How to stop AngularJS onClick event from causing scroll to jump to top of

As I work on developing a website using Angular JS and Bootstrap, I encountered an issue with the hamburger menu button on my homepage. Whenever I scroll halfway down the page and click the hamburger icon, it automatically scrolls me back to the top of the ...