我正在练习 VueJS 1.0,并且正在学习组件。
在这个example
, 有一个 input
元素和必须供应coupon
或某种 code
来自 API。我必须验证。我有我的 <coupon >
组件并具有 when-applied
的 Prop . when-applied
必须调用父函数 setCoupon
但它不会。
我只收到这个错误 this.whenApplied is not a function
.
<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);
}
}
});
有人请帮忙。非常感谢您的建议。
最佳答案
您应该绑定(bind)
属性:
<coupon v-bind:when-applied="setCoupon"></coupon>
或者您可以使用 v-bind
的简写语法:
<coupon :when-applied="setCoupon"></coupon>
阅读更多关于 props
的信息 here .
关于javascript - 在 VueJS 中将父函数传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34391454/