2015-06-30 61 views
6

我有一個問題,即將函數傳遞給組件的方式與文檔中指定的方式不一致。Vue.js將函數傳遞給不工作的道具

這是我app.js

methods: { 
    updateAnswer: function(question) { 
     console.log('question: '+question); 
    } 
} 

這是我的html文件:

<multiplechoice class="question counterIncrement counterShow active" id="q2" whenanswered="{{ updateAnswer('1') }}"></multiplechoice> 

這是我components.js文件:

props: [ 
    'whenanswered' 
], 

ready: function() { 
    this.whenanswered(); 
}, 

我已經試過這個:

props: [ 
    { name: 'whenanswered', type: Function} 
]; 

但仍然沒有運氣。

這是我的控制檯當我加載的頁面:

Uncaught TypeError: this.whenanswered is not a function 

任何幫助將是非常讚賞:)

回答

7

你可以這樣做:

<multiplechoice class="question counterIncrement counterShow active" id="q2" :whenanswered="updateAnswer('1')"></multiplechoice> 

如果沒有 ':'(與V-綁定)像你這樣只會發送一個字符串,而不是評價。即使有那些{{ }}

但請記住,您的updateAnswer函數應該返回一個函數。由於您的道具將執行updateAnswer('1'),並且您的multiplechoice實際上需要一個將在需要時執行的功能。

methods: { 
    whenanswered: function(question) { // or whenanswered (question) { for ES6 
    return function() { ... } // or() => {...} for ES6 
    } 
} 
-1

提琴會有所幫助,但基本上,你需要:

methods: { 
    whenanswered: function(question) { 
     ... 
    } 
} 

如果你想調用該功能。道具只是一個字符串,而不是一個函數。

例子:

<div id="app"> 
    Loading... 
    <data-table on-load="{{onChildLoaded}}"></data-table> 
</div> 

new Vue({ 
    el: "#app", 
    methods: { 
     onChildLoaded: function (msg) { 
      console.log(msg); 
     } 
    }, 
    components: { 
     'data-table': { 
      template: 'Loaded',  
      props: ['onLoad'], 
      ready: function() { 
       this.onLoad('the child has now finished loading!') 
      } 
     } 
    } 
});