简体   繁体   中英

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">
  <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! 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.

I tried adding @click="updateName(device.name)" to my <option> tag, and then that method would update the second data property.

However this only works on Firefox, since other browsers don't trigger a click event on <option> . Besides it feels like kind of a weird/hacky way to do this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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