2015-12-21 90 views
20

我正在VueJS 1.0中練習,並且正在學習組件。 在這個example,有一個input元素,並且必須從API提供coupon或某種code。我必須驗證。我有我的<coupon >組件,並有道具when-appliedwhen-applied必須調用父功能setCoupon但它不會。我只有這個錯誤this.whenApplied is not a function將父函數傳遞給VueJS中的子組件

<div id="demo" class="list-group"> 
     <script id="coupon-template" type="x-template"> 
      <input type="text" v-model="coupon" v-on:blur="whenCouponHasBeenEntered"> 
      <div v-text="text"></div> 
     </script> 
     <coupon when-applied="setCoupon"></coupon> 
    </div> 

這裏是我的app.js文件

Vue.component('coupon', { 
    template: '#coupon-template', 

    props: ['whenApplied'], 

    data: function() { 
    return { 
     coupon: '', 
     invalid: false, 
     text: '' 
    } 
    }, 


    methods: { 
    whenCouponHasBeenEntered: function() { 
     this.validate(); 
    }, 

    validate: function() { 
     if(this.coupon == 'FOOBAR') { 
     this.whenApplied(this.coupon); 
     return this.text = '20% OFF!!'; 
     } 

     return this.text = 'that coupon doesn`t exists'; 
    } 
    } 
}); 

new Vue({ 
    el: '#demo', 

    methods: { 
    setCoupon: function(coupon) { 
     alert('set coupon'+ coupon); 
    } 
    } 
}); 

有人請幫助。非常感謝的建議。

回答

23

你應該bind屬性:

<coupon v-bind:when-applied="setCoupon"></coupon> 

,或者你可以使用簡寫語法v-bind

<coupon :when-applied="setCoupon"></coupon> 

瞭解更多關於propshere