【发布时间】:2019-04-15 07:25:13
【问题描述】:
我正在尝试为功能组件的子组件/元素创建自定义事件处理程序。问题是当使用render() 函数创建子组件时,我无法访问它们的this 上下文。
假设我们有以下功能组件:
const Aggregate = {
functional: true,
props: {
value: Object // to work with v-model
},
render: function(createElement, context){
const template = []
const inputHandler = function(value, prop){
const data = Object.assign({}, context.props.value, { [prop]: value })
console.log(context.props.value)
console.log(data)
this.$emit('input', data)
}
for (const prop of Object.keys(context.props.value)){
const child = createElement('input', {
props: {
value: context.props[prop]
},
on: {
input: function(event){
// 'this' is not binded here - it is undefined,
// hence the inputHandler() function is
// rising an error
inputHandler.apply(this, [event.target.value, prop])
}
}
})
template.push(child)
}
return template
}
}
以这种方式创建事件处理程序时,是否可以访问 vnode 的 this 上下文?
附:用例信息:我想实现一个为资源自动生成<input> 元素并通过v-model 指令使用双向绑定的组件。我还想在<table> 中使用它,其中需要在<td> 中进行包装,因此我使组件功能化。
【问题讨论】: