Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html.

The code snippet I have been using looks something like this:

<tbody v-if="fields.length">
    <tr v-for="(item, index) in fields">
        <td>@{{ item.name }}</td>
        <td><input type="checkbox" id="checkbox" v-model="item.active"></td>
        <td>
            <button id="show-modal" @click="showModal = true">Show Modal</button>
        </td>
    </tr>
    <modal :item="item" v-if="showModal" @close="showModal = false">
        <h3 slot="header">Hello World</h3>
    </modal>
</tbody>


Vue.component('modal', {
    template: '#modal-template',
    data: function() {
        return {
            item: ''
        }
    }
});

Even though the button triggers the modal successfully, I encountered a warning stating that

Property or method "item" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
. Additionally, upon inspecting the modal component using Vue dev tools, the value of item remains as an empty string '', indicating that it is not being populated by the :item binding as expected.

Could someone guide me on the correct approach to pass the item object into the modal so it can be utilized within the window?

Answer №1

When passing the variable item from a parent component to a child component, you should avoid using data and instead use props!

Vue.component('modal', {
    template: '#modal-template',
    props: ['item'],
    data: function() {
        return {

        }
    }
});

Answer №2

Two important factors to consider:

  1. It is crucial to reference the item in the data object as a prop for the component rather than directly. For example, use props: ['item'].
  2. The modal should be within the loop's scope, which currently ends at the closing </tr> tag. To achieve this, modify the click action to trigger a method that takes the item and assigns it to a variable passed in like a prop. This approach involves changing from showModal = true to openModal(item). Then create a method that sets the required values. Here is an example:

    openModal(item) {
      this.showModal = true;
      this.modalItem = item;
    }
    
    ...
    
    data: () => {
      modalItem: null
      ...
    }
    

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

Searching for the index of a nested array in jQuery using JSON

I am currently working on developing an image uploader using Codeigniter3 along with jQuery and Ajax. Problem: I am facing difficulty in understanding how to locate the index of the array received from the ajax response shown below. Here is the data retu ...

How can you trigger an event when a table cell is selected and a key is pressed?

In my project, I have some td elements with a class name assigned to them. My goal is to trigger a pop-up window when one of these td elements is in focus and the F9 key is pressed. Here's what I've attempted so far: $(document.body).keypress(fu ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

Use jQuery to activate the radio button inside a div whenever it is triggered by a change

How can I check which radio button list is clicked and then send a jQuery ajax call for the clicked item? Currently, I have tables with the IDs plan1, plan2, plan3 generated using PHP. Each table has a radio button list. Using jQuery each, how can I achiev ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

Solving the pyramid of doom with Node.js

I have been struggling to find a way to simplify my code structure. Here is what I have come up with so far: router.use('/create', function(res,req,next) { try { var data = { startDate: new Date(req.body. ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

a pair of browser windows displaying a web application built with ASP.NET MVC

We are currently in the process of developing an ASP.NET MVC web application for internal use within our organization. Our users' productivity can greatly benefit from having a larger screen space, which is why we have decided to provide each user wit ...

Best practices for formatting dates in Node.js, Sequelize, MySQL, and Vue

I've been tasked with developing an internal system for a company in Slovakia. I've built an API using node.js (express.js server) and I'm utilizing Sequelize to query mysql. On the frontend, I'm using Vue with Vuetify. The issue I&apo ...

Guide on how to store a CSS image in a server using PHP

Looking to create a button generator using JavaScript on my website, similar to the one found here http://css-tricks.com/examples/ButtonMaker/. In addition to generating buttons, I also want to include a save button so that users can save the button image ...

Error message encountered in Rails Webpacker: "Uncaught TypeError: $(...).tooltip is not recognized as a function

I am working on a Rails 6 application where I compile assets using Webpack 4.39.1 with the help of the Webpacker gem. In my webpack configuration file (config/webpack/environment.js), I have included JQuery 3.4.1 and Popper.js as part of the ProvidePlugin ...

Error: Undefined Variable in Laravel Eloquent Query

I'm currently encountering an error and have included a screenshot for reference. In the log, I can see the value of the $team variable. Can anyone help me identify where I might be going wrong? https://i.sstatic.net/8dvk9.png ...

Stop the interval when the variable equals "x"

I've created a function that controls a specific row in my database using AJAX. The function is triggered by a click event and placed within a setInterval function to check ten times per second. Initially, it will return 0, but eventually (usually wi ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...