2017-04-16 66 views
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/ - 注意第一個按鈕是如何工作的,但第二個按鈕沒有,唯一的差異第二個按鈕是一個參數。任何人有任何想法發生了什麼?

在此先感謝!

回答

1

在子組件中,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) 
} 

回報什麼。 因此:

事件無效處理程序「單擊」:得到了未定義

你可以bind參數two的功能,如果這是你打算如何在這個fiddle使用它等。

+1

很確定你的意思是'this.action2.bind(null,'two')'在那個小提琴中(或者你想要的任何「this」)。 – Bert

+1

@BertEvans對不起,'this.action2.bind(this,'two')'可能是更好的選擇? –

+1

「綁定」的第一個參數是'this'將在綁定函數內。你說'這個'應該是'two'。 – Bert