Mastering the art of passing props in VueJS

My setup in the App is quite straightforward, with two main components: The HelloWorld component and a dialog component. The dialog component receives props from the HelloWorld component. The data in the HelloWorld component is rendered by looping over an array. What I am trying to achieve is that when I click on one of the elements, I want the dialog to be pre-filled with the name and age of the respective element. However, I'm unsure how to accomplish this.

You can view the complete setup on this CodeSandbox.

This is my Vuex Store:-

state: {
    userData: [
      {
        name: "Sam",
        age: "24"
      },
      {
        name: "Max",
        age: "28"
      }
    ],
    dialog: false
  },
  getters: {
    getUserData: state => state.userData,
    getDialog: state => state.dialog
  },
  mutations: {
    openDialog(state) {
      state.dialog = true;
    }
  }

This is my HelloWorld Component:-

<template>
  <v-container>
    <v-layout justify-center>
      <v-card>
        <v-card-text>
          <div v-for="user in getUserData" :key="user.age">
            <span>{{user.name}}</span>
            <span>{{user.age}}</span>
            <v-icon @click="openDialog">create</v-icon>
          </div>
        </v-card-text>
      </v-card>
    </v-layout>
    <Dialog/>
  </v-container>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import Dialog from "./Dialog";
export default {
  name: "HelloWorld",
  components: {
    Dialog
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getUserData: "getUserData"
    })
  },
  methods: {
    ...mapMutations({
      openDialog: "openDialog"
    })
  }
};
</script>

This is my Dialog Component:-

<template>
  <v-dialog v-model="getDialog" max-width="300px">
    <v-card>
      <v-card-text>
        <v-text-field v-model="title"></v-text-field>
        <div class="mt-5">{{age}}</div>
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  props: {
    title: {
      type: String
    },
    age: {
      type: Number
    }
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getDialog: "getDialog"
    })
  }
};
</script>

I appreciate all the assistance. Thank you.

Answer №1

<div v-for="(person, idx) in getUserInfo" :key="person.id">
        <span>{{person.name}}</span>
        <span>{{person.age}}</span>
        <v-icon @click="showDialogAndFetchUser(idx)">edit</v-icon>
 </div>
showDialogAndFetchUser(idx) {
   this.showDialog();
   /* set data to be passed to child components */
   this.currentName = this.getUserInfo[idx].name;
   this.currentAge = this.getUserInfo[idx].age;
}
<Dialog 
  :title="currentName"
  :age="currentAge"/>

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

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

Using Vue.js to update a variable in a parent component that is nested multiple layers deep

Check out my cool Vue Instance: const myApp = new Vue({ el: '#my-app', data() { return { trigger: true } }, components: { ChildComponentOne, ChildComponentTwo }, router, store, ...

Accessing properties of objects using specific keys

In my coffeescript code, I am attempting to retrieve the keys from an object where the key matches a specific value. However, in addition to the object's own properties, I am also getting function properties in my result. This issue is causing an err ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

Replicate a click using jQuery to retrieve a filtered multigallery based on the URL

I have a website that was built using Elementor for a photographer. The site features an Elementor Multigallery with a filter at the top. I am looking to create external links that will direct users to specific subpages showing only filtered items. For ex ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

"Strategically placing elements on an HTML grid

My current project involves creating a grid layout in HTML using CSS. The goal is to use this layout for various elements such as images, text, and links. What I envision is a visually appealing grid where each object fits together seamlessly with no gaps ...

Is it possible to store a JWT token in local storage when working with Next.js?

We are considering using Next.js for our application, with a focus on client-side rendering for data fetching. The API we will be interacting with is external and requires authentication to access specific user dashboard content. While the homepage will ...

A Guide to Accessing Numbered Properties within an Object

I am working with a large Object that has over 700 properties, all numbered. How can I efficiently iterate through each of these numbered properties? { '0': { emails: { categorized: [Object], all: [Object], primary: &a ...

Quickly redesigning the appearance of file input using javascript and jquery. Seeking assistance to correct css issues on jsfiddle

Hey there, I've been working on styling the input[type="file"] element and could use some assistance. Like the saying goes, "One JSfiddle is worth 1000 words," so here's the link to my example: --- For more details, click here: http://jsfiddle.n ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

What are the repercussions of labeling a function, TypeScript interface, or TypeScript type with export but never actually importing it? Is this considered poor practice or is there a potential consequence?

I find myself grappling with a seemingly straightforward question that surprisingly has not been asked before by others. I am currently immersed in a TypeScript project involving Vue, and one of the developers has taken to labeling numerous interfaces and ...

Issue with symbol not functioning on different device

There seems to be a display issue with the ...

No visible changes from the CSS code

As I create a small HTML game for school, I'm facing an issue with styling using CSS. Despite my efforts to code while using a screen reader due to being blind, the styling of an element isn't being read out as expected. The content seems to be c ...

When the LI element is clicked, it triggers the display of another LI element without affecting the rest of the

New to the web development scene and trying to figure out how to create a collapsible text feature using HTML, JavaScript, and JQuery. I've got the styling down but struggling with the scripting part. Here's an example of what I'm trying to ...

An appropriate loader may be required to manage this file type issue, which seems to be occurring consistently on all Vuetify components

Currently, I am working on a project that involves a rails backend and a Vue frontend. Both ends are functioning properly, and my next step is to enhance the visual appeal by incorporating Vuetify. After running vue install vuetify, I encountered Runnin ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...