简体   繁体   English

使用 Select 输入和 v-model 更新两个数据值

[英]Update two data values using a Select input and v-model

I have a simple Select input, binded to a data property ( device_id ) using v-model:我有一个简单的 Select 输入,使用 v-model 绑定到数据属性( device_id ):

<select v-model="device_id">
  <option disabled value="">Choose a device</option>
  <option v-for="device in devices" v-bind:value="device.id">
    {{ device.name }}
  </option>
</select>

When the user picks a device, this.device_id is updated automatically, which is great!当用户选择设备时, this.device_id会自动更新,这很棒! I can then save that to my database.然后我可以将其保存到我的数据库中。

However... I also want to save this.device_name and for the life of me, I can't figure out how to "bind" or update both this.device_id AND this.device_name when the user clicks on an option.但是......我也想保存this.device_name并且在我的一生中,当用户单击一个选项时,我无法弄清楚如何“绑定”或更新this.device_idthis.device_name

I tried adding @click="updateName(device.name)" to my <option> tag, and then that method would update the second data property.我尝试将@click="updateName(device.name)"到我的<option>标记中,然后该方法将更新第二个数据属性。

However this only works on Firefox, since other browsers don't trigger a click event on <option> .然而,这只适用于 Firefox,因为其他浏览器不会在<option>上触发点击事件。 Besides it feels like kind of a weird/hacky way to do this.此外,它感觉像是一种奇怪/hacky 的方式来做到这一点。

Just to be clear, my question is: How can I update two data properties when the user clicks on an option?为了清楚起见,我的问题是:当用户单击一个选项时,如何更新两个数据属性?

I am sure there is a "correct" way and I would love to hear your ideas!我相信有一种“正确”的方式,我很想听听你的想法! This feels like a very straightforward problem and yet I can't seem to figure it out -_-这感觉是一个非常简单的问题,但我似乎无法弄清楚-_-

Thanks in advance!提前致谢!

Try to bind the option value to the whole object and then work with properties of your selected one like :尝试将选项值绑定到整个对象,然后使用所选对象的属性,例如:

<select v-model="selected_device">
  <option disabled value="">Choose a device</option>
  <option v-for="device in devices" v-bind:value="device">
    {{ device.name }}
  </option>
</select>

to send the id to your database just use this.selected_device.id and you could also use selected_device.name将 id 发送到您的数据库只需使用this.selected_device.id ,您也可以使用selected_device.name

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

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