[英]Vue.js/JSX: Dynamic event name
I am writing a Vue.js component.我正在编写一个 Vue.js 组件。 The component renders an
<input>
element.该组件呈现一个
<input>
元素。 An event listener is listening to either change
or input
event, according to the value of a prop.根据 prop 的值,事件侦听器正在侦听
change
或input
事件。
How to write the render function with JSX?如何用 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)
},
})
},
}
I want to write something like this:我想写这样的东西:
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
}
You're almost there.您快到了。 Just a little tweak, like this.
稍微调整一下,就像这样。
<input
type="text"
v-on="{ [bindEvent]: e => this.$emit('update', e.target.value) }"
/>
See working implementation .请参阅工作实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.