What is the best way to pass an object into a method within a select element using Vue

Kindly review the following code snippet.

  <tr>
    <td>Select Timeslot</td>
    <td colspan="2">
      <select class="form-control" v-on:change="onTimeSlotClick">
        <option v-for="slot of slots">
          <label slot.time_from - slot.time_to</label>
        </option>
      </select>
    </td>
  </tr>

I am looking to pass the slot object to the onTimeSlotClick method. How can I achieve this? I attempted using onTimeSlotClick(slot) but it seems to return undefined in the onTimeSlotClick method.

Answer №1

When working with a select tag in Vue.js, ensure to use the v-model directive and set the value as an object.

var vm = new Vue({
  el: '#vue-instance',
  data: {
    rows: [
      {name: 'MacBook Air', price: 1000},
      {name: 'MacBook Pro', price: 1800},
      {name: 'Lenovo W530', price: 1400},
      {name: 'Acer Aspire One', price: 300}
    ],
    item:""
  },
  methods:{
    onTimeSlotClick: function(item){
      console.log(item);
      }

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
   <select class="form-control" v-model="item" v-on:change="onTimeSlotClick(item)">
         <option value="">Select</option>
        <option v-bind:value="row" v-for="row in rows">
          <label>{{row.name}}</label>
        </option>
      </select>
      <div>{{item | json}}</div>
</div>

Answer №2

Consider implementing a v-model attribute on the select element to achieve the desired functionality.

<tr>
    <td>Select Timeslot</td>
    <td colspan="2">
      <select class="form-control" v-model="selected" v-on:change="onTimeSlotClick(selected)">
        <option v-for="slot of slots">
          <label slot.time_from - slot.time_to</label>
        </option>
      </select>
    </td>
  </tr>

You have the option to either pass selected explicitly as shown in the example, or utilize onclick as a trigger and retrieve selected from its Vue-defined location.

If possible, try to minimize the use of event handlers. Utilizing reactive pipes can often simplify your code while making it more concise and expressive.

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

The React Native File generator

Currently, we are utilizing redux actions in our web project. In an effort to share logic between web and native applications, we have integrated these actions into our react native project with the intention of only having to modify the components. One o ...

Guide to transferring a JavaScript/Ajax variable to a PHP webpage with the help of AJAX

function initiateIperfSpeedRequest(speedVar, actualIp) { var xmlhttp = getAjaxObject(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { handleIperfResponse(xmlhttp.respo ...

The semantic UI search functionality is malfunctioning

My experience with semantic ui involves encountering an issue where the search result on a website appears empty, despite finding the JSON result in my console. This is the JavaScript code I am using: $('.ui.search').search({ apiSettings: { ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

Changing the boolean value in a database by invoking a function within an href link

Within the Laravel framework, I have a messages page that displays all messages associated with a particular user. Initially, these messages are marked as unread, so I implemented a button to toggle the boolean value in the database from 0 to 1 and then di ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

Ensure the accuracy of submitted form information

I am seeking to enhance the validation process for my form, which is already using jquery.validate.min.js for validation. I want to incorporate another layer of validation by making an ajax call to my MySQL database to check if the email address provided i ...

Can Firebase lists be reversed?

I have searched extensively on SO for an answer to this question, but I haven't found a solution yet. Therefore, please do not mark this as a duplicate. Currently, I am working with AngularFire in Angular 2 and Typescript. I am using FirebaseListObse ...

identify the vuetify slider display

I am currently working with a vuetify slide group and I need to programmatically identify which slides are fully displayed and which are partially displayed. https://i.sstatic.net/qQImO.png Based on the image above, it can be seen that slide 0 and slide ...

Execute the JS file to retrieve the initial port available within the npm script

Within my package.json, I have the following script: "dev": "webpack-dev-server --config webpack.dev.js --progress --port ${getPort()}", I've also installed a package called get-port, which allows me to set a default port and ...

Popovers in Bootstrap 4 do not have clickable Custom Forms

I find it strange that in Bootstrap 4, only custom forms are not clickable in the Bootstrap popover. It's interesting how default forms in Bootstrap 4 work just fine. Any suggestions on how to resolve this issue? Below is my code. Thank you for you ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

Enhancing jQuery UI elements (Customizing jQuery Datepicker to prevent incorrect entries)

My goal is to enhance the functionality of the jQuery UI Datepicker by adding validations. I have spent considerable time searching the internet for help without success. Although I came across a similar question on Stack Overflow jquery-datepicker-functi ...

How to utilize JavaScript to convert a string into a function name

In this specific scenario, I am required to trigger a function based on the data attributes associated with an HTML element. function func1(arg1){ alert("func1"); } function func2(arg2){ alert("func2"); } jQuery(document).on('click', & ...

Extensions for selecting and making Datatable responsive

Currently, I am working on integrating a Datatable into my products table. My goal is for it to be both responsive and include the select extension (checkbox for each column). I have successfully implemented both features. However, I noticed that when the ...

JS/JQuery: Retrieve value from dropdown list or input field

I'm looking for a way for my user to choose a value from a drop-down menu, but if they can't find the right option there, I want them to be able to input a custom value. I've figured out a workaround by deactivating the drop-down and activa ...

Can you place a v-snackbar underneath a temporary v-navigation-drawer?

Is it possible to stack the v-navigation-drawer over a v-snackbar with the "temporary" prop enabled? Typically, the snackbar obeys the navigation drawer when the app prop is set, except when the drawer has the temporary prop. While this behavior may make ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...