Home » vue » vuejs get selected value in custom dropdown component

vuejs get selected value in custom dropdown component

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m using a custom select component and trying to set the data prop selectedOffer to the value selected in the select, however $event is passing an empty value.

How can I set selectedOffer to the value of the dropdown?

offersList.vue

 <dropdown
              :options="userOffers"
              :value="selectedOffer"
              :item-title-key="'title'"
              :item-value-key="'id'"
              :item-id-key="'id'"
              @optionSelected="setSelectedOffer($event)" />

offersList.js

 data() {
    return {
      userOffers: [{title: 'aus ITA'},{title: 'aus DE'}],
      selectedOffer: '',
    };
  },
 methods: {
    setSelectedOffer(value) {
      this.selectedOffer = value;
      console.log(this.selectedOffer);
    },
  },

dropdown.vue

<select
          :id="id"
          :name="name"
          @change="$emit('optionSelected', $event.target.value)">
        <slot/>
        <option
            v-for="item in options"
            :title="item[itemTitleKey]"
            :value="item[itemValueKey]"
            :key="item[itemIdKey]">
          {{ item[itemTitleKey] }}
        </option>
      </select>
Answers:

See Using v-model on Components for a guide on custom form components.

The basic idea is that your component implements the v-model pattern by accepting a value prop and emitting an input event.

Vue.component("dropdown", {
  template: `
    <select @input="$emit('input', $event.target.value)">
      <slot>
        <option value="" :disabled="!!value">Select...</option>
      </slot>
      <option
        v-for="item in options"
        :title="item[itemTitleKey]"
        :value="item[itemValueKey]"
        :key="item[itemIdKey]"
        :selected="value == item[itemValueKey]"
      >
       {{ item[itemTitleKey] }}
      </option>
    </select>`,
  props: {
    value: [String, Number],
    options: Array,
    itemTitleKey: {
      type: String,
      default: "title"
    },
    itemValueKey: {
      type: String,
      default: "id"
    },
    itemIdKey: {
      type: String,
      default: "id"
    }
  }
})

new Vue({
  el: "#app",
  data: () => ({
    userOffers: [{id: 1, title: 'aus ITA'},{id: 2, title: 'aus DE'}],
    selectedOffer: null,
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <dropdown
    :options="userOffers"
    v-model="selectedOffer"
    item-title-key="title"
    item-value-key="id"
    item-id-key="id"
  ></dropdown>
  
  <pre>selectedOffer = {{ selectedOffer }}</pre>
</div>