簡體   English   中英

Vue.js/JSX:動態事件名稱

[英]Vue.js/JSX: Dynamic event name

我正在編寫一個 Vue.js 組件。 該組件呈現一個<input>元素。 根據 prop 的值,事件偵聽器正在偵聽changeinput事件。

如何用 JSX 編寫渲染函數?

{
  props: {
    lazy: Boolean,
  },
  render(h) {
    const bindEvent = this.lazy? 'change' : 'input'
    return h('input', {
      attrs: {
        type: 'text',
      },
      on: {
        [bindEvent]: e => this.$emit('update', e.target.value)
      },
    })
  },
}

我想寫這樣的東西:

render(h) {
  const bindEvent = this.lazy? 'change' : 'input'
  return <input
    type='text'
    on={{ [bindEvent]: e => this.$emit('update', e.target.value) }}
  />
}

解決方案 1:為每個事件添加事件監聽器

render(h) {
  const eventHandler = name =>
    (this.bindEvent === name)? e => this.$emit('update', e.target.value)
    : () => {}
  return <input
    type='text'
    onChange={eventHandler('change')}
    onInput={eventHandler('input')}
  />
}

方案二:給 VNode 添加事件監聽器

render(h) {
  const eventHandler = name =>
    (this.bindEvent === name)? e => this.$emit('update', e.target.value)
    : () => {}
  const vNode= <input type='text' />
  vNode.data.on = { [this.bindEvent]: e => this.$emit('update', e.target.value) }
  return vNode
}

您快到了。 稍微調整一下,就像這樣。

<input
  type="text"
  v-on="{ [bindEvent]: e => this.$emit('update', e.target.value) }"
/>

請參閱工作實施

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM