Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parent Function to Child Component in VueJS

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.

I only got this error 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

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.

like image 420
vistajess Avatar asked Dec 21 '15 08:12

vistajess


People also ask

How do I pass data from parent to child component in Vue?

component' you need to define the props passed in the child component. you need to call getCurrentUser() when the parent component initialises.

How do you call parent component to child component?

Call Child Component method from Parent Component A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular.


1 Answers

You should bind the property:

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

or you could use the shorthand syntax for v-bind:

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

Read more about the props here.

like image 161
Pantelis Peslis Avatar answered Oct 02 '22 08:10

Pantelis Peslis