hidar
hidar

Reputation: 5939

Vuejs returns [object Object] from data attribute

I have the following jsfiddle example (check the console) and all you will see is [object Object] instead of person data:

So, basically I have a vuejs instance and a div for v-for to iterate an object

<div id='app'>
  <p v-for="person in people[0]"> 
    <span> {{ person.name }}</span>
        <i class="fa fa-check" 
        v-bind:data-identity="person" 
        @click="addDetail($event)"></i>
  </p>
</div>

The problem is that if I echo {{ person }} I can see a JSON data on the page, but if I try to get it in the function addDetail() with e.target.dataset.identity then all I get is [object Object] and not the json data. I have tried JSON.parse and String methods, non of them work.

Upvotes: 3

Views: 21589

Answers (5)

przbadu
przbadu

Reputation: 6049

For me using JSON.stringify() solved that problem:

v-bind:data-identity="person"

will give data-identity="[object object]"

Where as:

v-bind:data-identity="JSON.stringify(person)"

will convert your json/object to string, and it will work

data-identity="{"id":1,"name":"User 1"}"

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 1220

Just passing handler method @click is enough. See Vue reference for event handling

Template:

<i class="fa fa-check" @click="addDetail(person)"></i>

JS:

methods: {
  addDetail: function (person) {
    console.log(person);
  }
}

Upvotes: 2

itzhar
itzhar

Reputation: 13031

in my case i have the same var name in html (inside v-for) & and in data function and everytime another var been used by browser...

Upvotes: 0

reinarg
reinarg

Reputation: 456

You shouldn't try to access "person" through event and the DOM but give it as parameter to the function addDetail

Template

<div id='app'>
  <p v-for="person in people[0]"> 
    <span> {{ person.name }}</span>
        <i class="fa fa-check" 
        @click="addDetail(person)"></i>
  </p>
</div>

Script

...
methods: {
  addDetail: function(person){
    console.log(person)
  }
}
...

Upvotes: 2

Nemani
Nemani

Reputation: 784

v-bind:data-identity="person" coverts person to string hence you can't attach an object to dataset as any object.toString() method returns [Object object] and you are getting the same

try to attach any string like person.name and see if it is reflected in your dataset

https://jsfiddle.net/qthg4Lwm/

hope this will help :)

EDIT: All data attributes are string read this article

from above article

Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5".

Upvotes: 3

Related Questions