Utilizing v-for to display dynamic data in a modal imported through slots

Issue: I'm facing an issue with passing data from a clicked card to a modal component. The modal should display the title, image, preview URL, and download URL of the card that was clicked. However, I'm encountering an error that says

is not defined on the instance but referenced during render

It seems like the data is not being passed into the modal even though I'm referencing the clicked card. I need a way to pass the index of the clicked card to the modal, but I'm not sure of the best approach to achieve this.

I'm currently using slots to handle the dynamic data from the v-for loop, and I hope I don't have to switch to props as it might complicate things.

Steps Taken:


        <!-- Cards -->
        <div class="card-wrapper">
          <div v-for="(card, index) in cards" :key="index" class="card">
            <div @click="showModal(card)" class="card-body">
              <img :src="card.img" alt="resource img" />
              <h4 class="card-title">{{ card.title }}</h4>
              <h6 class="card-subtitle">{{ card.subtitle }}</h6>
            </div>
          </div>
        </div>
<!-- MODAL -->
        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ img }} </template>
            <template v-slot:body>
              {{ title }}
              <div class="text-center mb-1 mt-2">
                <a :href="previewUrl"><button class="modal-btn btn btn-large">Preview</button></a>
                <a :href="downloadUrl"><button class="modal-btn btn btn-large">Download</button></a>
              </div>
            </template>
          </Modal>

DATA

`cards: [
        {
          title: "Card Title",
          subtitle: "Card subtitle",
          img: require("@/assets/images/test.jpg"),
          previewUrl: "https://test.com",
          downloadUrl: "https://test.com"
        },`

METHODS:

  `methods: {
    showModal(card) {
      this.isModalVisible = true;
      this.title = card.title;
      this.img = card.img;
      this.previewUrl = card.previewUrl;
      this.downloadUrl = card.downloadUrl;
      this.isModalVisible = true;
    },
    closeModal() {
      this.isModalVisible = false;
    }
  }`

The imported modal component

`<template>
  <div>
    <div class="modal-backdrop" @click.self="close">
      <div class="card relative">
        <button type="button" class="btn-close" @click="close">
          <i class="material-icons">clear</i>
        </button>
        <header class="modal-header mb-1">
          <slot name="header" />
        </header>
        <div class="mt-1 text-center">
          <slot name="header-sub" />
        </div>
        <slot name="body" />
        <footer class="text-center p-2">
          <slot name="footer" />
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "modal",

  methods: {
    close() {
      this.$emit("close");
    }
  }
};
</script>`

https://i.sstatic.net/hbIqD.jpg

https://i.sstatic.net/K4KUQ.jpg

Answer №1

It is important to populate the modal data before clicking to ensure the correct information is displayed.

For instance, in your data, initialize the modalInfo object with empty title and image properties:

{
modalInfo:{title:'',img:''}
}

Then, in the click event, update the modalInfo properties like this:

 showModal(card) {
      this.modalInfo.title = card.title;
      this.modalInfo.img = card.img;
      this.isModalVisible = true;
    }

Finally, for the modal section, ensure it is set up as follows:

        <!-- Cards -->
        <div class="card-wrapper">
          <div v-for="(card, index) in cards" :key="index" class="card">
            <div @click="showModal(card)" class="card-body">
              <img :src="card.img" alt="resource img" />
              <h4 class="card-title">{{ card.title }}</h4>
              <h6 class="card-subtitle">{{ card.subtitle }}</h6>
            </div>
          </div>
        </div>
<!-- MODAL -->
        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ modalInfo.img }} </template>
            <template v-slot:body>
              {{ modalInfo.title }}
              <div class="text-center mb-1 mt-2">
                <a :href="previewUrl"><button class="modal-btn btn btn-large">Preview</button></a>

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

Vue.js components may not always display the data that has been fetched

Within a Laravel view, there is a component where the data in the select tag sometimes doesn't show up. It's quite strange as it randomly displays the data and other times it doesn't. There are no errors being logged in the console or the vi ...

Unable to display texture and color on .obj files in Three.js

After introducing a new model in .obj and .mtl formats into my three.js code, I encountered an issue where the color of the model would turn white, regardless of its original color or texture. Below is a snippet of the code related to the pig model: // ...

`Is it possible to remove an empty frame using javascript?`

I have this script that generates a "layer" resembling a frame and I need to remove it. Here is the code for creating the layer: function disableLayer() { var layer = document.getElementsByTagName('div')[0]; d = document.createElement(& ...

There was an error encountered with the value used in the weak set at the time of adding it to WeakSet.add

I've been working on creating a test file for a Vue component, but I seem to be struggling with where I'm making mistakes. This is all new to me as I am just getting started with unit testing. Despite spending some time searching online, ...

Guide on establishing two loops in React JS

I'm receiving a JSON array that contains nested arrays. I attempted to iterate through it using two loops, but so far, I haven't been successful. {this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) => {alarms.repo ...

What is the process for creating and registering custom Handlebars functions?

Despite spending plenty of time searching, I am still unable to find detailed information on where exactly to place my custom handlebars helpers. Should they be added in a <script> tag within my webpage's .hbs file? Or should I include them in a ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Transferring information to a server with node.js

I have implemented AJAX to send data to the server. The code snippet I am using is: function post(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('POST', url); req.onload = function() ...

Utilizing jQuery in your webpack configuration for optimal performance

I encountered some issues while trying to test a simple project that involves using a jQuery function with webpack. The errors occurred during the bundling process and are as follows: ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot ...

Ways to troubleshoot an issue that arises when the `onChange` event is not utilized in a radio button component on a

When using this component for radio buttons without the Onchange function, I sometimes encounter the following error on the page related to onUpdate: TypeError: this.props.onUpdate is not a function onChange(e) { let value = e.target.value; this ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

jQuery.clone() Internet Explorer issue

I have a scenario where I use jQuery.clone() to extract the html of a page and then append it to a pre tag. Surprisingly, this operation works perfectly fine in Firefox and Chrome, but there's no response when it comes to IE: <!DOCTYPE html> &l ...

Internet Explorer freezing when running selenium executeScript

Hey everyone, I've spent the past couple of days scouring the internet trying to find a solution to my modal dialog problem. There's a wealth of helpful information out there and everything works perfectly fine except for Internet Explorer. Speci ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

JavaScript Intercept Paste function allows you to detect and capture data being past

I stumbled upon this code snippet while browsing through how to intercept paste event in JavaScript. The code works well for intercepting clipboard data before it's pasted, ensuring that essential "\n" characters are not lost during the process. ...

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

Navigating with vue-router using guard redirections

I am currently working with vue.js and I'm looking to implement a functionality where I can redirect a user to another URL within the navigation guard called beforeRouteEnter. The main objective is to check if the current city of the user is included ...

Assign a data attribute to each item in a loop within a Vue.js v

I am trying to create a Bootstrap accordion using a loop. However, I am encountering errors when trying to use the following code snippet: data-target="#collapse{{index}} <div v-for="(section, index) in model.Sections" class="panel panel-default" ...