简体   繁体   English

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

[英]Passing Parent Function to Child Component in VueJS

I'm having my practice in VueJS 1.0 and I am learning about Components. 我正在VueJS 1.0中练习,而且我正在学习组件。 in this example , there is an input element and has to supply coupon or some kind of a code from an API. 在这个example ,有一个input元素,并且必须从API提供coupon或某种code and I have to validate. 我必须验证。 I have my <coupon > component and has props of when-applied . 我有我的<coupon >组件,并且具有when-applied道具。 The when-applied must call the parent function setCoupon but it won't. when-applied必须调用父函数setCoupon但不会。

I only got this error this.whenApplied is not a function . 我只得到这个错误。当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>

Here is my app.js file 这是我的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. 建议非常感谢。

You should bind the property: 你应该bind属性:

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

or you could use the shorthand syntax for v-bind : 或者你可以使用v-bind的简写语法:

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

Read more about the props here . 阅读更多关于props 信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM