简体   繁体   English

如何使用Vue在选择中将对象传递给方法?

[英]How to pass object to method in select using vue?

Please check the below code. 请检查以下代码。

  <tr>
    <td>Select Timeslot</td>
    <td colspan="2">
      <select class="form-control" v-on:change="onTimeSlotClick">
        <option v-for="slot of slots">
          <label slot.time_from - slot.time_to</label>
        </option>
      </select>
    </td>
  </tr>

I want to pass slot object to onTimeSlotClick method. 我想将slot对象传递给onTimeSlotClick方法。 How can I do that? 我怎样才能做到这一点? I tried something like onTimeSlotClick(slot) but getting undefined in onTimeSlotClick method. 我尝试了类似onTimeSlotClick(slot)但是在onTimeSlotClick方法中变得undefined

Use v-model for select tag and set value as object 使用v-model选择标签并将值设置为对象

 var vm = new Vue({ el: '#vue-instance', data: { rows: [ {name: 'MacBook Air', price: 1000}, {name: 'MacBook Pro', price: 1800}, {name: 'Lenovo W530', price: 1400}, {name: 'Acer Aspire One', price: 300} ], item:"" }, methods:{ onTimeSlotClick: function(item){ console.log(item); } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script> <div id="vue-instance"> <select class="form-control" v-model="item" v-on:change="onTimeSlotClick(item)"> <option value="">Select</option> <option v-bind:value="row" v-for="row in rows"> <label>{{row.name}}</label> </option> </select> <div>{{item | json}}</div> </div> 

Try a v-model attribute on the select. 在选择项上尝试使用v-model属性。 So... 所以...

<tr>
    <td>Select Timeslot</td>
    <td colspan="2">
      <select class="form-control" v-model="selected" v-on:change="onTimeSlotClick(selected)">
        <option v-for="slot of slots">
          <label slot.time_from - slot.time_to</label>
        </option>
      </select>
    </td>
  </tr>

You can either pass selected explicitly, like in the example, or just use the onclick as a trigger, and read selected from wherever you defined it in your Vue. 您可以像示例中那样显式地传递selected内容,也可以仅使用onclick作为触发器,并从Vue中定义的任何位置读取selected

Without knowing your problem, try to avoid event handlers. 不知道您的问题,尝试避免事件处理程序。 You can often define what you want with reactive pipes, and your code will be shorter and more expressive. 您通常可以使用反应式管道来定义所需的内容,并且代码将更短且更具表现力。

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

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