[英]Vue.js/JSX: Dynamic event name
我正在編寫一個 Vue.js 組件。 該組件呈現一個<input>
元素。 根據 prop 的值,事件偵聽器正在偵聽change
或input
事件。
如何用 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) }}
/>
}
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')}
/>
}
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.