Search code examples
node.jsvue.jsv-forv-model

Vue.js, using v-model to get information from v-for


I have a dropdown box in a modal, that is populated with device objects. I want to show the user only the name value of each device object. It is doing this currently. But when the user selects one of the device names, I want to use v-model to store the _id of the device selected, not the name. I want this because the back end has to do a lot more work if I only have the name, instead of the _id.

Here is the template:

<template>
  <card-modal :visible="visible" @ok="buttonOK(selected)" @cancel="buttonCancel" :title="app.name" transition="zoom" :okText="'Add Device'">
    <div class="block">
      <p class="subtitle is-5">Choose a device to add to the app:</p>
      <select v-model="selected">
        <option v-for="device in devices">{{ device.name }}</option>
      </select>
      <span>Device: {{ selected }}</span>
    </div>
  </card-modal>
</template>

What is the best way for me to save the entire device object (or just the device._id) instead of just the device name, which is being selected by the user?


Solution

  • You just need to set the value attribute of the option element to be the _id of each object:

      <select v-model="selected">
        <option v-for="device in devices" :value="device._id">{{ device.name }}</option>
      </select>
    

    By assigning the value attribute, it will make the select element to have this value as the selected one.

    See an example:

    new Vue({
      el: '#app',
      template: `<div>
      Selected: {{ selected }}
       <select v-model="selected">
          <option v-for="device in devices" :value="device._id">{{ device.name }}</option>
        </select>
      </div>`,
      data() {
        return {
          selected: 1,
          devices: [
            { _id: 1, name: 'Device 1' },
            { _id: 2, name: 'Device 2' },
            { _id: 3, name: 'Device 3' },
          ]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"></div>