Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a select in vue's createElement?

I have a vue component that uses template, I'd like to change it to use render function, I know createElement('h1', 'title'), but how to use it with something like 'select' with all the options? here is the template based component:

https://jsfiddle.net/aaoehLqe/

<div id="app">
  <p>{{ message }}</p>
  <myselect  v-bind:option= "option" ></myselect>
  {{option}}
</div>
like image 287
AngeloC Avatar asked Mar 12 '17 01:03

AngeloC


1 Answers

Here is the select component with 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
          }
        }, 'Under 1'),
        createElement('option', {
          attrs: {
            value: 1
          }
        }, '1'),
      ]
    )
  },
})

You can see the working fiddle here: https://jsfiddle.net/aaoehLqe/1/

To understand how it works, you can see the API details of createElement in 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'
  ]
)
like image 59
Saurabh Avatar answered Nov 14 '22 23:11

Saurabh