简体   繁体   English

将对象绑定到vue.js中的element属性

[英]Bind object to element attribute in vue.js

Consider 考虑

<ul>
  <li v-for="o in objects" v-on:click="click"></li>
</ul>

where objects in something like 像这样的物体

var objects = [
    { derp: 1 },
    { derp: 2 },
];

in my click() function, I want to get access to o instance. 在我的click()函数中,我想访问o实例。

function click(event) {
    console.log(event.target.myObject);
}

<li v-for="o in objects" v-on:click="click" v-bind:data-myObject="o"></li>

and then getting the object using event.target.getAttribute("data-myObject") yields a string , not object . 然后使用event.target.getAttribute("data-myObject")获取对象会产生一个string ,而不是object

I can make this work using an index, and then lookup the object from this.$data.objects[index] . 我可以使用索引来完成这项工作,然后从this.$data.objects[index]查找对象。 This seems backward to me, as I expect some way of binding o instance to the target generated <li> element. 对我来说,这似乎是倒退,因为我期望将o实例绑定到目标生成的<li>元素的某种方式。

How to do this? 这个怎么做?

You need to pass object in calling function as in below example 您需要在调用函数中传递对象,如下例所示

 var app = new Vue({ el:'#app', data:{ myObj: [ { derp: 1 }, { derp: 2 }, ], output:'' }, methods:{ myFunc: function(obj){ this.output = obj; console.log(obj); } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <ul> <li v-for="o in myObj" v-on:click="myFunc(o)">{{o.derp}}</li> </ul> {{output}} </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM