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

"Vue Filepond: Enhancing Your Images with Cropping

Currently, I am integrating filepond with VueJS to facilitate image uploads. To enable image cropping during upload, a specific configuration is required. The filepond plugin has been globally registered, as shown below: import Vue from 'vue'; i ...

What strategies can be implemented to improve the total blocking time in Vue for optimal performance

I'm facing a challenge that I can't seem to resolve. My page has a high total blocking time (2+ sec). Despite trying to load every vue component asynchronously, the issue persists with 2+ sec TBT. I'm puzzled by what could be causing such a ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

What are the steps for building modules using Vuex and fetching data using mapState()?

I've been experimenting with separating my Vuex code into modules, but I'm having trouble retrieving data using mapState(). What's the most effective approach for creating modules and utilizing mapping? Here's the structure of my stor ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

I am encountering an issue with my authentication system where it is returning

I'm currently experiencing an issue with my authentication system using passport. For some reason, I keep getting an 'undefined' value returned. Can anyone provide assistance? Here is the code snippet in question: app.js passport.use(new L ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

How can you align the label of a v-text-field to the right in rtl languages?

I am working with a v-text-field in the following format: <v-text-field v-model="username" label="نام کاربری" /> However, I have noticed that the label appears on the left side. Is there a way to adjust it so that it displays on the right ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

Issue with Vue.js webpack encountering problems when importing a CSS file from an external library

I'm in the process of integrating the aos animation library into my testing app. I installed it using yarn add aos, and in my Vue application, I've included the following code: <script> .... import AOS from 'aos/dist/aos.js' imp ...

AngularJS - Retaining the initial value without submitting

On the left side, I have a list of users with corresponding details displayed on the right. The form handles the details on the right using inputs with ng-model. Whenever I click on a user from the left section, the selected user changes and the model auto ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

Is there a way to enlarge an iFrame to fill the entire screen with just a button click, without using JavaScript

I am currently attempting to achieve full screen mode for an iFrame upon clicking a button, similar to the functionality on this site. On that website, there is a bar that expands to full screen along with the embedded game, which is what I am aiming for. ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

Uploading files with Vue.js Element-UI and axios triggers unwanted page refresh

I am utilizing the element-ui file upload component() to manage the frontend of image uploading. All functionalities work flawlessly (file is successfully sent to the server, etc). However, for some reason, after the axios's successful response code r ...

A guide to displaying the date retrieved from a JSON data file API request using JavaScript

How can I display the date from a JSON data file API call using JavaScript? I am facing difficulty in showing the date on the dashboard display page. I am utilizing JavaScript with async-await for calling the API, and Bootstrap 4 for design. The function ...

Issue with uploading media on Wordpress: "Unfortunately, an error occurred during the upload process. Please attempt again at a later time."

Often times, when trying to upload media from the front-end, I encounter this issue: An error occurred during the upload process It seems like the error occurs sporadically, making it even more challenging to troubleshoot. Sometimes, when logging in fo ...