Javascript Vue.js/JSX:动态事件名称
我正在编写一个Vue.js组件。组件呈现一个Javascript Vue.js/JSX:动态事件名称,javascript,vue.js,vuejs-jsx,Javascript,Vue.js,Vuejs Jsx,我正在编写一个Vue.js组件。组件呈现一个 元素。事件侦听器正在侦听更改或输入 事件,根据道具的值 如何使用JSX编写渲染函数 { props: { lazy: Boolean, }, render(h) { const bindEvent = this.lazy? 'change' : 'input' return h('input', { attrs: { type: 'text', }, on: {
元素。事件侦听器正在侦听更改
或输入
事件,根据道具的值
如何使用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) }}
/>
}
渲染(h){
const bindEvent=this.lazy?'change':'input'
返回此值。$emit('update',e.target.value)}
/>
}
你就快到了。只是稍微调整一下,像这样
<input
type="text"
v-on="{ [bindEvent]: e => this.$emit('update', e.target.value) }"
/>
请参阅。解决方案1:向每个事件添加事件侦听器
渲染(h){
const eventHandler=name=>
(this.bindEvent===name)?e=>this.$emit('update',e.target.value)
: () => {}
返回
}
解决方案2:将事件侦听器添加到VNode
渲染(h){
const eventHandler=name=>
(this.bindEvent===name)?e=>this.$emit('update',e.target.value)
: () => {}
常数vNode=
vNode.data.on={[this.bindEvent]:e=>this.$emit('update',e.target.value)}
返回vNode
}
当然,这适用于模板,但不适用于渲染函数中的JSX。它编译成“指令”:[{name:“on”,value:{[this.bindEvent]:e=>{this.bindValue(e.target.value);}}}}}]
。控制台:[Vue warn]:无法解析指令:on
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
}