1
我試圖將一個點擊方法作爲道具傳遞給我的組件的孩子的孩子。但是,如果該方法不採用任何參數,它似乎可以正常工作。但是,如果需要參數,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/ - 注意第一個按鈕是如何工作的,但第二個按鈕沒有,唯一的差異第二個按鈕是一個參數。任何人有任何想法發生了什麼?
在此先感謝!
很確定你的意思是'this.action2.bind(null,'two')'在那個小提琴中(或者你想要的任何「this」)。 – Bert
@BertEvans對不起,'this.action2.bind(this,'two')'可能是更好的選擇? –
「綁定」的第一個參數是'this'將在綁定函數內。你說'這個'應該是'two'。 – Bert