如何在vue的createElement中创建一个select?

新手上路,请多包涵

我有一个使用模板的 vue 组件,我想将其更改为使用渲染函数,我知道 createElement(‘h1’, ‘title’),但是如何将它与带有所有选项的“select”之类的东西一起使用?这是基于模板的组件:

https://jsfiddle.net/aaoehLqe/

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

原文由 AngeloC 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 393
2 个回答

这是带有 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'),
      ]
    )
  },
})

你可以在这里看到工作小提琴: https ://jsfiddle.net/aaoehLqe/1/

要了解其工作原理,您可以在文档中查看 createElement 的 API 详细信息:

 // @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'
  ]
)

原文由 Saurabh 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以试试这个:

 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)))
  }
})

[ 演示]

请检查 v-if and v-for & v-model 部分。

原文由 Pantelis Peslis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题