Hi there, I am facing an issue with the modal window. Whenever I click on the image, it always displays the same image instead of the right one. Can you please suggest

The window opens, but instead of showing the image I clicked on, it displays the last image in the table. How can I fix this error? Below are my modal and map templates, which are the parent components of the modal. Thank you.

<template>
  <div class="modal-box" v-if="revealed">
    <div class="overlay"></div>
    <div class="modal card">
      <div @click="toggleModal()" class="btn-modal btn btn-danger">
        X
      </div>
      <h2>modal window</h2>
      <div><slot> </slot></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Modal",
  props: ["revealed", "toggleModal"],
  methods: {},
};
</script>

<style>
.modal-box {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.overlay {
  background: rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
.modal {
  background: white;
  position: fixed;
  padding: 50px;
}
.btn-modal {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>

Here is the parent component:

<template>
  <div>
    <div>
      <div
        class="pb-5 mx-5 px-5 d-flex flex-wrap justify-content-around align-items-center "
      >
        <div
          v-for="(image, id) in images"
          :key="id"
          class=" my-5 col-8 col-lg-4"
        >
          <div class="border-card shadow-card card ">
            <div role="button" @click="toggleModal(image)">
              <img
                class="top-img card-img-top"
                :src="image.link"
                alt="photo-onMySite"
              />
            </div>
            <modal v-bind:revealed="revealed" v-bind:toggleModal="toggleModal">
              <img :src="image.link" :class="`img-id--${id}`" alt="" />
            </modal>

            <div class="bg-secondary topDivColor"></div>
            <div class="card-body">
              <h5 class="card-title">{{ image.name }}</h5>

              <button @click="toggleShow(image)" class="btn btn-secondary">
                Details
              </button>

              <p :id="image.id" class="hidden pt-3 card-text"></p>

              <button
                class="ml-3 btn-card btn-secondary"
                @click="clickLink(image)"
              >
                View Project
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Modal from "./imageModal.vue";
export default {
  name: "card",
  components: {
    modal: Modal,
  },
  data() {
    return {
      revealed: false,
      images: [
        // array of images with their details
      ],
    };
  },
  methods: {
    // methods for showing, hiding, and clicking images
  },
};
</script>

<style lang="scss">
.top-img {
  height: 370px;
}
.topDivColor {
  height: 40px;
  width: 100%;
}
.border-card {
  border: 0.5mm ridge#a6b622ff !important;
}
.shadow-card:hover {
  box-shadow: 0 0 0 0 #748928ff;
  animation: pulse 1.3s infinite;
}
.shadow-card {
  box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175);
}
.hidden {
  display: none;
}
@keyframes pulse {
  to {
    box-shadow: 0 0 0 18px rgba(0, 0, 0, 0.01);
  }
}

</style>

The last link in the image array is displayed in the modal window, but I want the clicked image link to be displayed instead. https://i.sstatic.net/gj1yw.png

Answer №1

The method toggleModale in your code does not have an image parameter; instead, it controls the revele property for all modals. To address this, you can create an openModalId variable in the parent component to keep track of the currently-open modal, initializing it to 0. Then, you can pass the image ID to the toggleModale method like this:

Template:

<div role="button" @click="toggleModale(id)">
...
<modale :revele="openModalId === id" @toggleModale="toggleModale">

Method:

toggleModale(imageId) {
  this.openModalId = imageId;
}

Furthermore, you should also pass the image ID to modaleImage.vue and call toggleModale(id) from within that component. Alternatively, consider updating the component to utilize an $emit instead:

modaleImage.vue:

<div @click="$emit('toggle')" class="btn-modale btn btn-danger">
  X
</div>

Parent:

<modale :revele="openModalId === id" @toggle="toggleModale(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

Is it possible to utilize the package.json "resolutions" field to replace lodash with lodash-es?

Is it possible to use resolutions in a similar manner as dependencies, but with a different package? I'm specifically curious if this can be done with NPM or Yarn. "resolutions": { "lodash": "npm:lodash-es@^14.7.x" ...

Understanding the sequence of operations in Javascript using setTimeout()

If I have the following code: function testA { setTimeout('testB()', 1000); doLong(); } function testB { doSomething(); } function doLong() { //takes a few seconds to do something } When I run testA(), what happens after 1000 mill ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Encountering an issue while trying to import the D3.js library into my React.js application

I'm having trouble with properly importing the d3.js libraries in my react.js app. I am using import * as d3 from 'd3' to import everything and store it in the d3 namespace, but I keep getting an error that says - Cannot read property ' ...

Images and CSS are failing to load on Magento2

After downloading and installing Magento 2, I encountered a 404 error for scripts and css. A specific example of my image path is: I attempted to address this issue with the following solution: By opening up app/etc/di.xml and locating the virtualType ...

Having trouble building with vue-chartjs (4.1.1) in Nuxt (3.0.0-rc.4)? Looking for a way to implement a basic pie chart in your Nuxt project?

I've been trying to incorporate a reactive pie chart into my Nuxt app using chart.js for quick and efficient results. However, I've hit a roadblock as most resources I find online are for older releases. To help troubleshoot the issue, here is a ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

A guide on efficiently inserting multiple rows containing JSON data into a MySQL database simultaneously using node.js

I'm facing an issue with inserting multiple values into columns simultaneously. Let's say I have JSON data consisting of two rows of information, and I want to insert both rows into my table at one go. My attempt looks like this: var data = [&apo ...

Utilizing null values within the map function in React JS

I am currently developing an application using React JS. The app displays a list of users along with the status of books (available, taken, or requested) for each user. However, I'm encountering an issue where even after filtering out the books based ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

Vue.js - Communicating attribute names with a Child component

Currently, I am in the process of developing a Vue SelectComponent. One of the requirements I have is to pass the name of the Select as an attribute to the component like this: <select-component selectName="providers"></select-component> With ...

Running only failed tests in Protractor can be achieved by implementing a custom script that

I've encountered a problem in my JavaScript file where some of the test cases fail intermittently, and I want to rerun only those that have failed. Is there any feature or solution available that can help with this issue? It's quite frustrating a ...

What advantages does using immutablejs offer compared to using object.freeze?

I've scoured the internet trying to find convincing reasons for using immutablejs instead of Object.freeze(), but I still haven't found a satisfactory answer! What are the advantages of working with non-native data structures in this library ove ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Issue with cross-origin security when applying HTML5 video tag to a webGL texture

I am trying to link a remote video to a texture in WebGL. To allow the video source to be different from the document source, I added Access-Control-Allow-Origin:* to the http headers of the video source. Additionally, I set an anonymous origin for the vid ...

What could be the reason that data-bs-placement="right" is not functioning as expected?

I am facing an issue with the popover functionality in my project. No matter what value I set for data-bs-placement attribute, it does not display correctly. Can you help me understand why this is happening? <!DOCTYPE html> <html lang="en ...

Ways to address the problem of returning assignments

I encountered an issue while working on my code Error message: Arrow function should not return assignment no-return-assign The problematic code snippet is as follows: await DB.Place.find( match, // key to filter (err, doc) => (listOfObje ...