Passing information from Vue to a modal

I'm working with 3 components: TaskList, TaskItem, and TaskForm.

Within the TaskList component, there is a loop that renders all the data in TaskItem. Each TaskItem has an edit button meant to open a TaskForm modal (using bootstrap) displaying the specific task data.

TaskForm.vue

  
    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" id="formModal">
        // Modal content here
    </div>

TaskList.vue

  
    <div class="container">
        // TaskItem loop
    </div>

TaskItem.vue

  
    <div class="row align-items-center p-2 border rounded mt-2">
        // Task details
        <button class="btn btn-primary" @click="showForm = !showForm" data-bs-toggle="modal" data-bs-target="#formModal">
            <i class="bi bi-pencil-square"></i>
        </button>
    </div>

    <TaskForm v-if="showForm" :task="props.task"/>

However, I've encountered an issue where each modal displays the first task's name instead of the selected one.


While this approach works for now, I believe there might be a better way to achieve my goal (editing a list item). If anyone has a more efficient solution, I would love to hear it.

Answer №1

If you want to optimize your code, consider using the TaskForm component just once by utilizing props and emits in the following manner:

// Parent Component
<template>
<ChildComponent v-for="item in items" :key={item.id} :item="item" @edit-item="showEditModal" />
<PopUpComponent v-if="selectedItem !== null" :selected-item="selectedItem" @close="selectedItem = null" />
</template>
<script setup>
import {ref} from "vue";
const selectedItem = ref(null);
function showEditModal(item) {
selectedItem.value = item;
}

</script>

To enable the child component to trigger the modal, define an emit named edit-item as shown below:

// Child Component
<template>
..other data
<button @click="editItem">Edit</button>
</template>
<script setup>
const emit = defineEmits(["edit-item"]);

function editItem() {
emit('edit-item', props.item); // This will call the @edit-item in parent component which will then render the modal with selected item
}
</script>

Similarly, implement a close function for the modal:

<template>
...
<button @click="closeModal">Close</button>
</template>
<script setup>
const emit = defineEmits(["close"])
function closeModal() {
emit("close")
}
</script>

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

Display a list of dates within a specified range using the ng

Utilizing the ng-repeat directive to connect data with a filter for name search: <div ng-repeat='myoldrecs in myoldrec | filter:q as results '>......</div> $scope.myoldrec = [{name:ccc,date:13-02-2016},{name:ddd,date:14-02-2016}]; &l ...

Using alphabets or Roman numerals as an index in a Vuejs For loop: A step-by-step guide

In the Vue.js v-for loop, the default iterator starts from 0, 1, 2, 3... But how can we set the v-for to start index with i, ii, iii, or a, b, c instead of numbers? For example, consider the following content: let content = [ "Content1", &quo ...

What steps can you take to convert your current menu into a responsive design?

I am currently developing a website using PHP, HTML, and CSS. The site is not responsive, and I want to make the menu responsive. My global navigation and admin interface are not adapting properly as they are designed using tables. Is there a method I can ...

How can I resolve the Error: Element type is invalid?

https://i.sstatic.net/9PehR.jpgI am encountering the error message displayed above, and I am uncertain about the cause of this issue. In the code snippet below, I am fetching data from a file named Data.js located in my root folder. When I run the app, I r ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Tips on obtaining the data count from using the $.get method

Here is the code I'm currently working with: $.get('getstatsAccepted' + tickerid, {tickerid: tickerid}, function(data) { alert(data.length); }, 'json'); I am interested in obtaining the numbe ...

jQuery is working perfectly on every single page, with the exception of just one

Check out my code snippet here: http://jsfiddle.net/9cnGC/11/ <div id="callus"> <div class="def">111-1111</div> <div class="num1">222-2222</div> <div class="num2">333-3333</div> <div class="num3">444-4444< ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

The second asynchronous function relies on the completion of the first

Despite dedicating two days to exploring async/await and promises, I am still unable to make it work correctly. The challenge lies in the fact that the second await for b relies on the result of the first a. It seems no matter what approach I take, b keep ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

Codeigniter code to retrieve dynamic data in a select box

I am trying to implement a functionality where selecting an option from one dropdown will dynamically populate the options in another dropdown based on the selection. I believe I need to use an onchange function, but I'm unsure how to retrieve data fr ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

The tooltip feature in jQuery is experiencing some stuttering issues

Sometimes, images can convey messages better than words. I encountered a strange issue with my self-made jQuery tooltip. I prefer not to use any libraries because my needs are simple and I don't want unnecessary bloat. When I move my mouse from righ ...