What is the best way to add a dropdown menu in Vue using the createElement method?

I'm looking to transition a Vue component from using templates to render functions. I understand how to use createElement('h1', 'title'), but I'm unsure of how to apply it when working with elements like 'select' that have multiple options. Below is an example of the template-based component:

https://jsfiddle.net/aaoehLqe/

<div id="app">
  <p>{{ message }}</p>
  <myselect  v-bind:option= "option" ></myselect>
  {{option}}
</div>

Answer №1

Check out this snippet featuring the select component using createElement:

Vue.component('myselect', {
  props: ['option'],
  render: function(createElement) {
    var self = this
    return createElement(
      'select', {
        domProps: {
          value: self.option.value
        },
        on: {
          input: function(event) {
            self.option.value = event.target.value
          }
        }
      }, [
        createElement('option', {
          attrs: {
            value: 0
          }
        }, 'Less than 1'),
        createElement('option', {
          attrs: {
            value: 1
          }
        }, '1'),
      ]
    )
  },
})

To see it in action, view the live example here: https://jsfiddle.net/aaoehLqe/1/

To gain a better understanding of how it functions, refer to the API documentation for createElement in Vue.js official docs:

// @returns {VNode}
createElement(
  // {String | Object | Function}
  // An HTML tag name, component options, or function
  // returning one of these. Required.
  'div',
  // {Object}
  // A data object corresponding to the attributes
  // you would use in a template. Optional.
  {
    // (see details in the next section below)
  },
  // {String | Array}
  // Children VNodes. Optional.
  [
    createElement('h1', 'hello world'),
    createElement(MyComponent, {
      props: {
        someProp: 'foo'
      }
    }),
    'bar'
  ]
)

Answer №2

Based on your fiddle, here is a simple version that you can use.

Vue.component("mySelect", {
  props:["value"],
  render(h){
    const vm = this;
    let options = [];
    for (let c = 0; c < 18; c++)
      options.push(h("option", {
        domProps:{innerHTML: c},
        attrs:{value: c},
      }))
    return h("select",{
      domProps:{
        value: this.value.value
      },
      on:{
        input(event){
          vm.$emit('input', {value:event.target.value})
        }
      }
    }, options)
  }
})

Answer №3

Consider giving this a try:

Vue.component('myselect', {
  props: ['option'],
  data () {
    return {
      items: [
        //
      ]
    }
  },
  render (h) {
    var self = this

    return h('select', {
      class: { 'form-control': true },
      domProps: { value: this.option.value },
      on: {
        input (event) {
          self.option.value = event.target.value
        }
      }
    }, this.items.map((item) => h('option', {
      attrs: { value: item }
    }, item)))
  }
})

[view demo]

Please take a look at the v-if and v-for & v-model sections.

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

What is the best approach for looping through this JSON data?

After retrieving the following JSON data from a database using ajax: {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]} What is the best approach for iterating over it to extract latitude and longitude p ...

Error in Alchemy: Can someone explain why maxFeePerGas must be greater than or equal to maxPriorityFeePerGas?

I've been following a tutorial at . The twist is that I'm attempting to send ETH to the Ropsten test faucet. async function main() { require('dotenv').config(); const { API_URL, PRIVATE_KEY } = process.env; const { createAlchemyWe ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Using nextjs9 to render .svg files within an img tag

Currently working on upgrading a Migration project from Nextjs7 to Nextjs9, and encountering difficulties when trying to include .svg files in the image tag. If you'd like to see a DEMO of this issue, please visit: https://codesandbox.io/s/nextjs-mh9 ...

Please include text beneath the input group addon class

Hey everyone, I'm facing some issues with my layout. Whenever the input fields are empty or null, I encounter errors. I want to ensure that the input text and input group addon have equal heights. Also, upon clicking the submit button, I use jquery/aj ...

Assign a property to an object following the execution of the query

I am currently utilizing node express to achieve a specific functionality. I encountered an issue while attempting to populate a field with data from another field. To resolve this problem, I decided to retrieve the value from another query and then assign ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Storing information from a form into an existing array using AngularJS

My script.js file contains an array like this: $scope.companies = [ { id: '1', contact: 'John Doe', address: '123 Main Street, USA', function: 'Customer', ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

Looking to showcase the array list on the user interface

I'm attempting to use the map function in JavaScript to display a list, but I keep encountering an error that says "TypeError: Cannot read property 'map' of undefined". import React, { Component } from 'react' import constants fro ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

javascript - increase counter by milliseconds

I am looking to enhance my JavaScript quiz counter by adding milliseconds. Currently, the quiz only tracks and displays time in seconds (stored in MySQL as a number of seconds, like 120 for 2 minutes displayed as 02:00). I now want to include milliseconds ...

Minimize unnecessary Vue component calls by consolidating data retrieval in a single component

Embarking on my Vue journey, I encountered an issue with data manipulation. I am passing a JSON data array from Flask to Vue and need to perform operations on it (such as getting the sum or average). I handle the processing in a single Vue component and r ...

How to prevent an element with a certain class from being selected in jQuery

How can I display the product name in an alert box when either the image or link is clicked on a product page? Currently, clicking the "Buy Now" button also triggers the popup alert, which I want to exclude using jQuery. Here is my current code: <scrip ...

Using Javascript to navigate links in a list using keyboard arrow keys

When links are not wrapped in other elements, I am able to change focus easily. Here is how it works: HTML <a id="first" href="#" class='move'>Link</a> <a href="#" class='move'>Link</a> <a href="#" class=&a ...

Attempted to create registrations for two views using the identical name RCTScrollView

Having trouble running my React Native app on iOS, I keep getting an error while the Android version works perfectly fine. Does anyone have any insight on this issue? XCode 11.5, RN 0.61.5, Using React Native CLI I've searched multiple sites but hav ...

What sets apart .andReturn(...) from .respondWith(...) when running AJAX call tests in JavaScript using Jasmine?

While utilizing the jasmine-ajax library for testing JavaScript code, I have discovered a way to mock ajax responses. There are essentially two methods to achieve this: Method #1: jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, contentT ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Exploring JavaScript's capability to parse JSON data

Having some trouble extracting information from the Google Maps API into my application using JavaScript. I'm struggling to figure out how to access the data in the returned JSON object. var site = "./maps/scripts/reverseGeocode/locale.php"; ...

What is the best way to clear an InputField when the user switches the RadioField selection?

I am currently using shadcn and react-hook-form. In my form, I have a Radiobutton that triggers an additional input field if the user selects yes. The issue I'm facing is when the user selects yes, fills out the extra input field, and then changes the ...