0

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>
2

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

and how would I get it to display the title instead of id as the value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.