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

organize a data set using react's hook system

Trying to sort an array using react hooks but the state is not updating. Any help on what could be going wrong? import React, { useState } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const dogs = [{ name: "fido", age: 22 }, ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Is it possible to refresh an iframe with PHP once a certain condition is satisfied?

I have a situation with two pages - one is my PHP script and the other is an HTML page containing two iframes. > <html> > > <iframe name=1></iframe> <iframe name=2></iframe> > > </html> Currently, ifram ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Vue. Where should this snippet be placed?

After delving into Vue, we were inspired by the concept of a store, which allowed us to separate page state from presentation. We developed an alert component that showcased the content of the alert string stored in store.pageError. As we aimed to incorpo ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

Tips on implementing .on() with querySelector in jquery?

Can you help me convert the jQuery code below into a querySelector method? <script type="text/javascript"> jQuery(function($){ $('#woocommerce-product-data').on('woocommerce_variations_loaded', function() { $ ...

Combining react-draggable and material-ui animations through react-transition group: a comprehensive guide

Trying to incorporate react-draggable with material-UI animations. One approach is as follows: <Draggable> <Grow in={checked}> <Card className={clsx(classes.abs, classes.paper)}> <svg classN ...

Encountered an error while trying to create module kendo.directives using JSPM

I am attempting to integrate Kendo UI with Angular in order to utilize its pre-built UI widget directives. After running the command jspm install kendo-ui, I have successfully installed the package. In one of my files, I am importing jQuery, Angular, and ...

The Quasar test fails to locate elements with a name tag>null<

I've encountered a strange issue while trying to conduct unit tests on my Quasar application. The problem seems to be that the test is unable to locate elements with the name tag, except for the q-route-tab components. I've experimented with diff ...

"Utilizing PHP with FTP and AJAX, or other comparable technologies

After successfully creating a PHP class for FTP server interaction (connecting, changing directories, uploading files, etc.), I am now eager to provide real-time updates to users about the actions happening on the server. For example, notifying them with m ...

Conceal a different CSS class if a certain CSS class is present on the page

I am currently working on organizing my page to distinguish between purchased and unsold products. For the items that have been bought, I am using the CSS class "winning_bid" within a div element. My goal is to hide another div with the class "price" if th ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

How can we monitor the value of $route.params.someKey in Nuxt.js?

When working with Nuxt.js, I am trying to keep track of the value associated with a key called key1 in the $route.params. The values for key1 are determined using a function called someFunction(). Is there a way for me to monitor $route.params.key1 as a ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

When attempting to load the table from JSON, the error message "Cannot read property 'name' of null" occurs in the fooplugins/Footable plugin

I am facing an issue while trying to integrate the "FooTable" plugin with ajax calls. Everything works perfectly fine when I directly input the JSON data or load it from a JSON file using $.get('....json'). However, when attempting to fetch the t ...

Exploring how process.argv in NodeJS can be utilized within JavaScript code compiled by

I'm having trouble compiling a basic TypeScript file using webpack (with 'awesome-typescript-loader') that needs to access command line arguments. It seems like the compiled JavaScript is causing a problem by overriding the Node 'proce ...

Using Angularjs to bind an array element within an ng-repeat inside a directive

Having trouble displaying the elements of an array using ng-repeat with a directive. The binding is not working correctly and showing empty values. To view the code, visit http://jsfiddle.net/qrdk9sp5/ Here is the HTML: <div ng-app="app" ng-controlle ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...