2015-12-21 92 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