What is the best way to pass card data between Vue.js components?

My application consists of two components: DisplayNotes.vue, which displays data in card format retrieved from the backend, and UpdateNotes.vue, which allows users to update existing data by opening a popup. The issue I'm facing is that when a user clicks on a card, the popup should open with the corresponding data from that card. How can I achieve this? Clicking on the 4th card should populate the popup-card with the content, could you please assist me in solving this problem?

DisplayNotes.vue

<template>
<div class="carddisplay-section" >
    <div v-for="note in notes" :key="note.id"  id="blur" class="container note">
        <div @click="toggle(note.id)" class="card-content">
            <h5>{{note.title}}</h5>
            <p>{{note.body}}</p>
        </div>
        <div class="import-icons">
            <icons class="imported-icons note-icons" />
            <button v-if="flag" class="card-button" type="button" @click="handlesubmit();Togglebtn();">Close</button>
        </div>
    </div>
    <div id="popup">
        <UpdateNotes :cardId="clickedCard"/>
    </div>
</div>
</template>

<script>
import service from '../service/User'
import icons from './icons'
import UpdateNotes from './UpdateNotes.vue'
export default {
    name: 'DisplayNotes',
    components: {
        icons,UpdateNotes
    },
    data() {
        return {
            flag: true,
            notes: [{
                id: 1,
                title: 'Fundoo',
                body: 'unlimited notes..'
            }, ],
           clickedCard:'',
        }
    },
    methods: {
        Togglebtn() {
            this.flag = !this.flag;
        },
        async handlesubmit() {
            service.userDisplayNotes().then(response => {
                this.notes.push(...response.data);
            })
        },
        toggle(id){
            var blur=document.getElementById('blur');
            blur.classList.toggle('active');
             this.clickedCard = id;

            var popup=document.getElementById('popup');
            popup.classList.toggle('active');

        },
    }
}
</script>

<style lang="scss">
@import "@/styles/DisplayNotes.scss";
</style>

UpdateNotes.vue[popup]

<template>

<div v-if="flag==false" class="update">
    <form class="update-note" @submit.prevent autocomplete="off">
        <input name="title" v-model="title" placeholder="Title" />
        <textarea name="content" v-model="body" style="resize: none" placeholder="Take a note..." rows="3"></textarea>
        <div class="btm-icons">
            <icons />
            <button id="btn-section" type="submit" @click="handlesubmit();flip();">Close</button>
        </div>
    </form>
</div>

</template>

<script>
import icons from './icons.vue'
import service from '../service/User'
export default {
    components: {
        icons
    },
    props: ['cardId'],
    data() {
        return {
            title: '',
            body: '',
            flag: false,
        }
    },
    methods: {
        flip() {
            this.flag = !this.flag;
        },
        async handlesubmit() {
            let userData = {
                id: this.cardId,
                title: this.title,
                body: this.body
            }
            service.userUpdateNotes(userData).then(response => {
                alert("Note updated  successfully");
                return response;
            })
        }
    }
}
</script>

<style lang="scss" scoped>
@import "@/styles/UpdateNotes.scss";
</style>

Answer №1

Make sure to pass the data of the currently clicked card in the popup, just like you pass the id of the card.

UpdateNotes.vue

<template>

<div v-if="flag==false" class="update">
    <form class="update-note" @submit.prevent autocomplete="off">
        <input name="title" v-model="title" placeholder="Title" />
        <textarea name="content" v-model="body" style="resize: none" placeholder="Take a note..." rows="3"></textarea>
        <div class="btm-icons">
            <icons />
            <button id="btn-section" type="submit" @click="handlesubmit();flip();">Close</button>
        </div>
    </form>
</div>

</template>

<script>
import icons from './icons.vue'
import service from '../service/User'
export default {
    components: {
        icons
    },
    props: ['cardId', 'cardContent'],
    data() {
        return {
            title: '',
            body: '',
            flag: false,
        }
    },
    created () {
        this.title = this.cardContent.title;
        this.body = this.cardContent.body;
    },
    methods: {
        flip() {
            this.flag = !this.flag;
        },
        async handlesubmit() {
            let userData = {
                id: this.cardId,
                title: this.title,
                body: this.body
            }
            service.userUpdateNotes(userData).then(response => {
                alert("Note updated  successfully");
                return response;
            })
        }
    }
}
</script>

<style lang="scss" scoped>
@import "@/styles/UpdateNotes.scss";
</style>

DisplayNotes.vue

<template>
<div class="carddisplay-section" >
    <div  v-for="note in notes" :key="note.id"  id="blur" class="container note">
        <div @click="toggle(note.id)" class="card-content">
            <h5>{{note.title}}</h5>
            <p>{{note.body}}</p>
        </div>
        <div class="import-icons">
            <icons class="imported-icons note-icons" />
            <button v-if="flag" class="card-button" type="button" @click="handlesubmit();Togglebtn();">Close</button>
        </div>
    </div>
    <div id="popup">
        <UpdateNotes :cardId="clickedCard" :cardContent="cardContent"/>
    </div>
</div>
</template>

<script>
import service from '../service/User'
import icons from './icons'
import UpdateNotes from './UpdateNotes.vue'
export default {
    name: 'DisplayNotes',
    components: {
        icons,UpdateNotes
    },
    data() {
        return {
            flag: true,
            notes: [{
                id: 1,
                title: 'Fundoo',
                body: 'unlimited notes..'
            }, ],
           clickedCard: '',
           cardContent: {}
        }
    },
    methods: {
        Togglebtn() {
            this.flag = !this.flag;
        },
        async handlesubmit() {
            service.userDisplayNotes().then(response => {
                this.notes.push(...response.data);
            })
        },
        toggle(id){
            var blur=document.getElementById('blur');
            blur.classList.toggle('active');
            this.clickedCard = id;

            this.cardContent = this.notes.filter((note) => note.id === id);

            var popup=document.getElementById('popup');
            popup.classList.toggle('active');

        },
    }
}
</script>

<style lang="scss">
@import "@/styles/DisplayNotes.scss";
</style>

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

Double injection of Redux-saga

I've encountered a strange issue with my redux-saga - it's being called twice instead of just once. Here is the action that triggers the saga: export function createRequest (data) { return { type: CREATE_REQUEST, payload: {data} }; ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

What are the different ways to share data between components in React?

There are two components in my code, one named <Add /> and the other named <Modal>. The <Add /> component has a state for handling click events. Whenever the <Add /> component is clicked, the state is set to true. I need to utilize ...

"Sharing JSON data with the client side using Express and Node.js: A step-by-step guide

I am currently working on an application that requires sending form data through XMLHttpRequest. The process involves validating the form data on the server side and then providing feedback to the client based on the validation result. In this project, I a ...

Angular's parent div height can be adjusted using CSS transitions

I have implemented a CSS transition to create a sliding effect in my pagination. However, I am facing an issue where the height of the containing div changes even when I set the position of the transitioned elements. Here is a snippet of my CSS: .slide { ...

Can you help me convert this Mongoose code to use promises?

Using Mongoose's built-in promise support, I aim to streamline the process of a user sending a friend request to another user. However, even with careful error handling and sequencing in place, I find myself grappling with a slightly condensed pyramid ...

What is the best way to utilize the sx prop in Material UI for applying styles specifically when the component is active or selected?

In the code snippet below, I have set up the useState hook so that when a ListItem is clicked on, the selected state becomes true. My goal is to apply specific styling when an item is selected using the sx prop instead of creating a styled component for su ...

When refreshing a JavaScript array of objects, it creates duplicate entries within the array

Currently, I am developing a chat application within a Vue project and experimenting with different features. A fully-featured chat app must have the ability to live-update "seen" states. This means that when one user views the last sent message, the othe ...

What if there was a magical jQuery method that could automatically trigger a callback function? What could it possibly be named?

Is there a way to load only images and iframes, similar to the .load() function? I want to automatically add a selector element into the "this" variable for this purpose. $('document').ready(function({ $('a').<Something to trigg ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

Sequential JavaScript Operations

What is the most efficient approach for executing sequential operations in JavaScript (specifically with Node.js)? For example, creating a folder - copying a file - editing a file, and so on. Since this is a stand-alone application, it is acceptable to u ...

Connecting AngularJS with select options

I am currently developing a checkout feature that calculates shipping prices based on the selected country. If the user picks United States, it should display US. For any other country selection, it should show Not US While the shipping function correctly ...

Tips on sending JSON string from Controller action to View and utilizing it as a parameter for a JQuery function

$(document).ready(function () { function initializeMap(data) { var map; alert(data); map = new L.Map('map', { zoom: 8, layers: [OSM] }); var array = $.parseJSON(data); alert( ...

Using JavaScript, what is the method for inputting values into a window.prompt()?

I've been working on a project that involves scraping basic HTML pages from an internal server at my workplace. When I visit these pages, a popup window similar to a windows.prompt() appears, asking for a username and password with the message "Enter ...

Issues with the visibility of React Bootstrap components

I'm troubleshooting an issue with the carousel on my website. When I try to load the page, the carousel appears blank. To set up the carousel, I used npm to install react-bootstrap. The carousel code can be found at . Upon checking the web console, ...

Is it possible to turn off the fallback color for bourbon radial gradients?

Is there a way to prevent the fallback from being applied when using the radial gradient mixin in Bourbon? I've consulted the documentation at , which states that the fallback is optional. However, no matter what I attempt, it seems that the primary ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Adjust the colors of two elements by clicking a button's onclick event

As stated in the title, I have a button in the books component. When this button is clicked, the color of a div within the books component and another div in the navbar component should change. - Below is the code for the books component : export class Bo ...

Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find. This is the code on my serve ...