What is the method for retrieving the key value of a chosen card?

Here is the code snippet from my template:

<v-item-group v-model="selectedAddress">
  <v-row class="mx-n6">
    <v-flex v-for="{id, title, address} in userAddresses" :key="id" sm12 md6 lg6 class="px-2">
      <CheckDeliveryAddress
        :id="`check-address-${id}`"
        :data-testid="`checkAddress${id}`"
        :title="title"
        :address="address"
      />
    </v-flex>
  </v-row>
</v-item-group>
<rw-button
  class="save-check-btn my-2"
  xs-flex
  color="primary"
  data-testid="saveCheckAddress"
  text="Submit"
  @click="commitCheckAddressSelection"
/>

This template utilizes a component for displaying addresses in cards. I have a question regarding extracting the id prop from the selected card. Can you provide guidance on how to achieve this?

<template>
  <v-item v-slot="{active, toggle}" :value="address">
    <rw-card :id="id" interactive :selected="active" dense @click="toggle">
      <rw-card-title>
        <h3>{{ title }}:</h3>
      </rw-card-title>
      <rw-card-body>
        <div>{{ address.addressLine1 }}, {{ address.addressLine2 }}</div>
        <div>{{ address.city }}, {{ address.state }}</div>
        <div>{{ address.zipCode }}</div>
      </rw-card-body>
    </rw-card>
  </v-item>
</template>

<script>
export default {
  name: 'CheckDeliveryAddress',
  props: {
    id: {type: String, required: true},
    title: {type: String, required: true},
    address: {type: Object, required: true},
  },
  data: () => ({}),
};
</script>

Answer №1

Within the function CheckDeliveryAddress, make sure to update the v-item's value by incorporating the id so that it can be passed on to the parent's selectedAddress. One way to achieve this is by binding the value to a computed property that includes both the id and address:

<template>
  <v-item :value="value">
    ...
  </v-item>
</template>

<script>
export default {
  props: {
    id: /*...*/
    address: /*...*/
  },
  computed: {
    value() {
      return {
        id: this.id,
        address: this.address,
      }
    }
  }
}
</script>

https://codesandbox.io/s/stoic-sanne-gzsrq?fontsize=14&hidenavigation=1&module=%2Fsrc%2Fcomponents%2FCheckDeliveryAddress.vue&theme=dark

Answer №2

Imagine a situation where your child component CheckDeliveryAddress is attempting to send data to its parent component.

In Vue, the only way to achieve this is by using an event emitter.

You can accomplish this by calling:

this.$emit('parent-event-method-name', data1, data2);

within the parent component.

<v-flex v-for="{id, title, address} in userAddresses" parent-event-method-name="methodName"
:key="id" sm12 md6 lg6 class="px-2">

methods:{
    methodName:function(data1, data2){

    }
}

CheckDeliveryAddress component structure:

<template>
      <v-item v-slot="{active, toggle}" :value="address" @click="raiseEvent">
        <rw-card :id="id" interactive :selected="active" dense @click="toggle">
          <rw-card-title>
            <h3>{{ title }}:</h3>
          </rw-card-title>
          <rw-card-body>
            <div>{{ address.addressLine1 }}, {{ address.addressLine2 }}</div>
            <div>{{ address.city }}, {{ address.state }}</div>
            <div>{{ address.zipCode }}</div>
          </rw-card-body>
        </rw-card>
      </v-item>
    </template>
export default {
      name: 'CheckDeliveryAddress',
      props: {
        id: {type: String, required: true},
        title: {type: String, required: true},
        address: {type: Object, required: true},
      },
      data: () => ({}),
      methods:{
        raiseEvent:function(e){
           this.$emit('on-card-select', this.id);//this.id is selected card id
        }
     }
    };

Your Parent component setup:

template:
'<v-item-group v-model="selectedAddress">
              <v-row class="mx-n6">
                <v-flex v-for="{id, title, address} in userAddresses" :key="id" sm12 md6 lg6 class="px-2" on-card-select="handleCardSelect">
                  <CheckDeliveryAddress
                    :id="`check-address-${id}`"
                    :data-testid="`checkAddress${id}`"
                    :title="title"
                    :address="address"
                  />
                </v-flex>
              </v-row>
            </v-item-group>
    <rw-button
              class="save-check-btn my-2"
              xs-flex
              color="primary"
              data-testid="saveCheckAddress"
              text="Submit"
              @click="commitCheckAddressSelection"
            />'

methods:{
   handleCardSelect:function(cardId){
      console.log(cardId);
   }
}

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

Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source. My attempt with the .attr() ...

Array of initials for full names in JavaScript

const nameList = ['John Doe', 'Jack Lock', 'Nick Load']; const initials = nameList.map([n]) => n); console.log(initials); I'm attempting to display the initials of the array items, but I'm only able to retrieve t ...

How to retrieve the nearest sibling in AngularJS without using jQuery

Is there a way to access the nearest element in Angular without using jQuery, like the example below demonstrates with jQuery? link: function (scope, element, attrs) { function handler($event) { if(!($event.target).closest(element).length) { ...

Triggering controller actions in JavaScript with bootgrid

How can I trigger a Bootstrap Modal that is located in a partial view within a controller using jQuery-Ajax and Bootgrid's JavaScript? var grid = $("#grid").bootgrid({ ajax: true, url: "/Currency/listCurrencyJson", formatters: { ...

The express.js and passport.js middleware in my application are functioning properly and executing as expected, however, there seems to be an issue with the

I have been working on developing a node/express server and decided to implement passport-local for user authentication using a local MongoDB server. I am encountering an issue where the page does not redirect as expected after submitting the login form wi ...

Issue with nested directive not triggering upon page load

I recently started working with AngularJS and came across an issue with nested directives. In my project, I have two directives: MainDir.js (function(){angular.module("mod").directive("mainDir", function(){ return { restrict: "E", scope: {}, ...

Vue Router with a Dynamic Twist

In my exploration, I am delving into whether utilizing a vue router would be the most effective method for the specific situation outlined below: The challenge I am facing involves a page that contains an unknown number of div elements, each with unique c ...

Is there a way for a button to automatically delete its corresponding index in an array upon being clicked?

I am currently developing a multiple choice quiz where users can input their own questions and answers to create a quiz. I am facing an issue with allowing users to delete questions stored in the question bank. Here is what I have tried so far: bodyText ...

Is it possible to create a fast function using vue's @click directive?

Is it feasible to create something similar to the following: <buttton @click="function(){alert('Yoohooo')}"></button> Without needing to define a method in the Vue instance for every instance of @click, especially for simple tasks l ...

Can anyone recommend a super sleek drop-down navigation menu that includes both images and text descriptions?

My interest has been piqued on how to create a menu similar to the one on with all the images and text details. Does anyone have any insights on the technologies utilized for this? Are there any commercial options available that offer a similar functiona ...

Adding options to a select element using JavaScript dynamically

Is there a way to create a dynamic select list for year values using JavaScript? <form action="something"> some other fields <select id="year"> </select> </form> ...

Tips for utilizing a variable name with ajax in jQuery

Currently, I have the following code that is a part of an autocomplete ajax query. The code is returning JSON and is functioning correctly with the provided code snippet. However, my goal is to enhance the auto complete function by making it more generic ...

Ways to present a pop-up dialog box featuring word corrections

I have developed a word correction extension that encloses the incorrect word in a span element. Upon hovering over the word, a drop-down menu with possible corrections should be displayed. However, my current code is not functioning properly. How can I en ...

Move all the attributes from one object stored in an array to another object within the same array using JavaScript or TypeScript

Is there a more efficient way to copy or move properties from one object within an array to another object? I've devised a simple logic that works, but I'm confident there must be a better approach. Can anyone offer some advice? var first = [ ...

Handling synchronous reception with Socket.io

Dealing with socket.io has been quite frustrating lately. I've spent about an hour trying to tackle this issue, but there isn't much helpful information available online. Due to JavaScript's synchronous nature, finding relevant details on th ...

Guide on adjusting the language settings for notifications in chosen.js?

Is it possible to customize the error message that appears in chosen.js when an unavailable option is typed into the multiple select box, which currently says 'No results match "query"'? ...

Incorporating a protected Grafana dashboard into a web application

I am looking to incorporate Grafana into my web application using AngularJS. The main objective is to allow users to access the Grafana UI by clicking on a button within my application. Setting up an apache reverse proxy for Grafana and ensuring proper COR ...

Creating a gaming application with Phaser.js and Ionic with subpar rendering capabilities

Attention developers! I recently created a game app using Phaser.js. I integrated the code into an Ionic blank starter app, allowing the Ionic framework to render the view while Phaser takes care of displaying the game. Issue: The game is a simple flapp ...

Real-time data update with Socket io: instantly refresh data on another page upon form submission without having to manually

What is the best way to utilize socket io in a situation where I have two pages open, one displaying a table of existing data and the other featuring a form for users to input new data? I want the table page to automatically update whenever a user submits ...

Would you suggest this approach for creating a personalized form component in vue 3?

CustomInput.vue <template> <input v-model="customModelValue"> </template> <script setup lang="ts"> import {computed} from "vue"; const customEmit = defineEmits(['update:customModelValue']) ...