How to retrieve the chosen option in a personalized dropdown component with Vue.js

I've encountered an issue with my custom select component where the data prop selectedOffer is not being set to the value selected in the dropdown, as $event seems to be empty.

Is there a way to assign the selected value from the dropdown to selectedOffer?

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>

Answer №1

For detailed instructions on using v-model with custom form components, you can refer to the Using v-model on Components guide.

The main concept involves implementing the v-model pattern in your component 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When querying a document, the Mongoose array is missing

When querying for documents with an array, I'm encountering an issue where the returned documents do not include the array. Below is my code: Query Code (async () => { const data = await Lesson.find({signed: {$exists: true}}); cons ...

AngularJS: Double the power of Ajax. Can you assist me?

ajax was successful twice. Take a look. https://i.sstatic.net/QLdpT.png https://i.sstatic.net/zAbXW.png ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Component variables do not update their values

I am facing an issue where the input field inside a component is not updating its value. Is there something that I have overlooked? By the way, I am using Vue 3. Child Component (input-form.vue) <template> <input type="text ...

The perplexing problem of scrolling in Dojox/mobile/scrollableview

I've noticed some scroll issues with the dojox/mobile/ScrollableView (version 1.10+) in my cordova application, specifically on Android phones. This problem seems to be affecting other widget-based architectures and even some store apps as well. I wou ...

Extract a property from a JSON object

Is there a way to access the href properties and use them to create multiple img elements with their sources set as the extracted href properties? I'm looking for a solution in either javascript or jQuery. I attempted the following code, but it didn& ...

Navigation menu featuring unique links for varying pages

This application is built on Ruby on Rails, using Ruby version 2.1.4 and Rails version 4.1.14. I have a Javascript dropdown menu in the header bar that displays a list of items. However, I'm struggling to figure out how to dynamically change the menu ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

Update the existing JSON object by incorporating a new property:value pair

I currently have a JSON object structured as follows: var data = {ID: 123, Name: "test"} My goal is to include an additional property and value in the data object based on a condition set by an inline if statement. The desired output should be: data = ...

Rapidly refreshing user interface in real-time based on current status

I'm struggling to create a button that will smoothly open a menu. Initially, I thought setting the state on button click would work fine but now I realize that the first click does not have any effect on the state or class. It's only the second a ...

The deferred type in Typescript that extends T is unknown at this time

While reviewing code in a library, I came across the line unknown extends CustomTypes[K]. My understanding is that this is a deferred type where unknown can always be assigned to CustomTypes[K]. However, I am unsure how this type is utilized and in what ...

Stop data from being submitted on the search form when entered

In my form, there is a search box within the form component. I have created two methods, one for searching and the other for submitting data. Every time I enter something in the search box, both methods are triggered. I used @submit.prevent="saveFormData" ...

Ensuring telephone numbers are properly validated using regular expressions

I have a regex for validating telephone numbers that is working for most cases except one. ^(\+?\ *[0-9]+)([0-9 ]*)([0-9 ])*$|(^ *$) The requirements are: 1. Allow only numeric values 2. Allow plus sign only at the beginning The ...

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

Starting a Vue.js app with preloaded data

I have a single file component named Foo: <template> <div> This is the main app. X is {{ x }}, y is {{ y }} </div> </template> <script> export default { data() { return { x: 'hello x' }; }, } </script> ...

What causes performance issues when utilizing mouseover events in JQuery?

var mouseX; var mouseY; $(document).mousemove( function(e) { mouseX = e.pageX; mouseY = e.pageY; }); $(".test").mouseover(function(){ $('#DivToShow').css({'top':mouseY,'left':mouseX, 'display':'block&ap ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Utilizing Vue.js and Axios to Send Object to API

I have been working on updating my API array by using axios and Vue.js. My goal is to implement the functionality that allows me to add a new object and have it displayed on the timeline. However, I am facing an issue where when I try to post a new title, ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...