在VueJS中将父函数传递给子组件

Passing Parent Function to Child Component in VueJS

本文关键字:组件 函数 VueJS      更新时间:2023-09-26

我正在VueJS 1.0中进行练习,我正在学习组件。在该example中存在input元素并且必须从API提供coupon或某种code。我必须验证。我有我的<coupon >组件,并且有when-applied的道具。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的信息。