组件中未定义Vue.js方法
问题描述:
我试图将一个点击方法作为道具传递给我的组件的孩子的孩子。但是,如果该方法不采用任何参数,它似乎可以正常工作。但是,如果需要参数,Vue.js会向我发送一个Invalid handler for event "click": got undefined
错误。组件中未定义Vue.js方法
这里是我的*组件:
new Vue({
el: '#app',
created: function() {
},
methods: {
action1: function() {
console.log('--action 1--')
},
action2: function (word) {
console.log('--action 2--', word)
}
}
});
这里是我的子组件:
Vue.component('parent-component', {
template: '#parent-component',
data() {
return {
menuItems: [
{
label: 'Action 1',
onClick : this.action1
},
{
label: 'Action 2',
onClick : this.action2('two')
}
]
}
},
props: ['action1', 'action2']
});
<template id="parent-component">
<action-menu :actions="menuItems"></action-menu>
</template>
这里是我的最低水平组件:
Vue.component('action-menu', {
template: '#action-menu',
props: ['actions'],
});
<template id="action-menu">
<div>
<div v-for="action in actions">
<button @click="action.onClick">{{ action.label }}</button>
</div>
</div>
</template>
这里是我的小提琴 - http://jsfiddle.net/11sfg1p8/ - 注意第一个按钮是如何工作的,但第二个按钮没有,唯一的差异第二个按钮是一个参数。任何人有任何想法发生了什么?
在此先感谢!
答
在子组件中,menuItems的第二个元素有一个onClick属性,它不是函数,而是函数的返回值。
发现其中的差别密切:
menuItems: [
{
label: 'Action 1',
onClick : this.action1 // assigning a function
},
{
label: 'Action 2',
onClick : this.action2('two') // assigning a value
// because of invocation of the function,
// which essentially returns undefined.
}
]
undefined
返回,因为函数:
action2: function (word) {
console.log('--action 2--', word)
}
回报什么。 因此:
事件无效处理程序“单击”:得到了未定义
很确定你的意思是'this.action2.bind(null,'two')'在那个小提琴中(或者你想要的任何“this”)。 – Bert
@BertEvans对不起,'this.action2.bind(this,'two')'可能是更好的选择? –
“绑定”的第一个参数是'this'将在绑定函数内。你说'这个'应该是'two'。 – Bert