Tips for transferring an object from data attributes to methods within a VueJS component

Check out this complete example first: https://jsfiddle.net/3bzzpajh/

I'm facing a challenge where I want to pass the entire person object to the method showSelectedData. However, when I try to attach the person object to a data attribute like :data-person="person", it turns into something like [object Object], making it unusable within my method:

<div id="app">
  <select name="" id="" @change="showSelectedData($event)" >
    <option :value="person.name" :data-name="person.name"  v-for="person in people[0]"> {{ person.name }}</option>
  </select>
</div>

In the code above, I am currently passing the person's name like :data-name="person.name", but this approach becomes cumbersome when the person object has multiple properties.

This is the context of my Vue.js application:

new Vue({
  el: '#app',
  data () {
    return {

      people: [{
        '1': {
          'code': 1010,
          'name': 'sam',
          'status': 'ACTIVE',
          'class': 'RED',
          'currencyCode': 'CHF'
        },
        '2': {
          'code': 1210,
          'name': 'jane',
          'status': 'ACTIVE',
          'class': 'WHiTE',
          'currencyCode': 'NA'
        },
        '3': {
          'code': 7777,
          'name': 'luis',
          'status': 'ACTIVE',
          'class': 'BLUE',
          'currencyCode': 'DE'
        },
        '4': {
          'code': 443,
          'name': 'dave',
          'status': 'ACTIVE',
          'class': 'GREEN',
          'currencyCode': 'FR'
        }
      }]

    }
  },
  methods: {
    showSelectedData: function (event) {
      console.log(event.target.selectedOptions[0].dataset.name)
    }
  }
})

Therefore, how can I access the person object inside showSelectedData when a dropdown option is selected?

Answer №1

In Vue, the common approach is to connect a data element to a select using v-model.

Create a data element named selectedPerson.

data:{
  selectedPerson: null,
  ...
}

Link it with v-model.

<select v-model="selectedPerson">

Set the person as the value for options.

<option :value="person" v-for="person in people[0]"> {{ person.name }}</option>

Now, once a person is chosen, selectedPerson will be the complete person object. You won't need to use the change event, bind it to data or search for it by index. Simply access the selected person through the data value when needed.

Answer №2

To efficiently keep track of the selected object in Vue, you can utilize the v-model to store the key of the chosen object and retrieve the full person object using this saved key later on. Alternatively, you have the flexibility to use any unique identifier, such as an object ID, for referencing and retrieving the related object effortlessly.

<div id="app">
  <select name="" id="" @change="displaySelectedInfo($event)" v-model="current_person_key">
    <option :value="index" :data-name="person.name"  v-for="(person, index) in people[0]"> {{ person.name }}</option>
  </select>
</div>

new Vue({
  el: '#app',
  data () {
    return {
      current_person_key: -1,
      people: [{
        '1': {
          'code': 1010,
          'name': 'sam',
          'status': 'ACTIVE',
          'class': 'RED',
          'currencyCode': 'CHF'
        },
        '2': {
          'code': 1210,
          'name': 'jane',
          'status': 'ACTIVE',
          'class': 'WHiTE',
          'currencyCode': 'NA'
        },
        '3': {
          'code': 7777,
          'name': 'luis',
          'status': 'ACTIVE',
          'class': 'BLUE',
          'currencyCode': 'DE'
        },
        '4': {
          'code': 443,
          'name': 'dave',
          'status': 'ACTIVE',
          'class': 'GREEN',
          'currencyCode': 'FR'
        }
      }]

    }
  },
  methods: {
    displaySelectedInfo: function (event) {
        var person = this.people[0][this.current_person_key];
        console.log(person)
    }
  }
})

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

Issue with static resource fetching when referencing a .js file within an HTML document while using Flask

My HTML file loads my OpenLayers JavaScript file (which displays a map frame) when opened directly. However, when running the HTML from my Flask python app, the JavaScript file/object fails to load (resulting in no map display, just some heading text). I ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

Exploring the Integration of Material UI DatePicker with Firestore in ReactJS: Converting Firestore Timestamps to Date Format

The database is correctly recording the date, however, when displayed, the DatePicker does not recognize the date from the database as it is in timestamp format (seconds and nanoseconds). <DatePicker margin="normal" label="Data do pedido" ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

Insert the user's choice as a MenuItem within the Select component

I currently have a default list of options for the user. However, I want to allow users to add their own category dynamically. This will trigger a dialog box to appear. How can I modify my code so that the value property starts from number 4? Take a look ...

What is the best way to paginate a dynamically updated data table using AJAX in Laravel?

I'm currently facing an issue with rendering a Blade template in Laravel. The template includes an HTML table populated with data fetched via AJAX, and I need to implement manual pagination using Laravel's LengthAwarePaginator. The main Blade fi ...

Ways to conceal components of an external widget on my site

I'm attempting to add a chat widget to my website and I'm looking to hide specific elements within the widget. The chat function is provided by Tidio, but I believe this applies to most widgets. My main goal is to conceal a button that minimize ...

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue. Take a look at the screenshot and code snippet provided: function myF ...

Is Vue capable of recording and tracking all user interactions - perhaps for testing purposes?

Over the past few months, I have been working on developing a Vue one-page application. We are nearing the end of the alpha version and will soon deliver it to our clients for real live testing. However, our end-users are regular office workers with no pro ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...

AngularJS radio button slider with ng-model and ng-checked functionality

I'm facing an issue where my ng-model is not getting updated when I cycle through radio button images using arrows instead of clicking on the image. How can I resolve this? HTML <div ng-repeat="contact in contacts" ng-show="showContactID == ...

Encountered a SyntaxError while deploying Nuxt.js SSR on Passenger: The import statement cannot be used outside a module

I am currently in the process of deploying my Nuxt app on a hosting service that uses Passenger to run Node.js applications. After building the app with the command ">npm run build" and deploying the content from the .nuxt folder onto the server, specif ...