在VueJS中将父函数传递给子组件 [英] Passing Parent Function to Child Component in VueJS

查看:661
本文介绍了在VueJS中将父函数传递给子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VueJS 1.0中练习,而且我正在学习组件。这个示例中的
,有一个输入元素,并且必须提供优惠券来自API的或某种代码。我必须验证。我有<优惠券> 组件,并且在应用时具有的道具。 何时应用必须调用父函数 setCoupon 但不会。

I'm having my practice in VueJS 1.0 and I am learning about Components. in this example, there is an input element and has to supply coupon or some kind of a code from an API. and I have to validate. I have my <coupon > component and has props of when-applied. The when-applied must call the parent function setCoupon but it won't.

我只收到此错误 this.whenApplied不是函数

    <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);
    }
  }
});

有人请帮助。建议非常赞赏。

Someone pls help. Suggestions pretty much appreciated.

推荐答案

你应该 bind 属性:

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

或者您可以使用 v-bind

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

详细了解道具 这里

这篇关于在VueJS中将父函数传递给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆