1

Assuming that I have a component 'test-component' that has a method getGeoEmailData() that fetches some data by making an Ajax call. If I am using the component like this:

<test-component v-bind:item="item" ></test-component>

I want to call getGeoEmailData() automatically (after parent prop 'item' has been bound to the component prop 'item') How do I do this?

2
  • you mean if item is true, you want to get something from getGeoEmailData from inside the component? Commented Dec 15, 2017 at 21:51
  • Call it in the created lifecycle hook. Commented Dec 15, 2017 at 23:12

1 Answer 1

3

First of all, if you want to get a data from inside your component, you have to emit from withing the components methods using it using emit method ex:

methods: {
  emitSomething () {
    this.$emit('foobar', 'some data')
  }
}

Now from your component you can listen listen event and pass it to your local methods using this syntax:

<my-component v-on:foobar='handler'></my-component> 

Now just created a method called handler to get what is emitted from the child.

If you want to get the emit content once your component binds to a value, just use a watcher: {} to watch when property is set to true.

This example will show you how when item changes to true, you can get the emit from the child component.

Vue.component ('my-component', {
  template: `<p> </p>`,
  props: ['item'],
  watch: {
    item (val) {
      if(val) {
        this.getSomething(); 
      }
    }
  },
  methods: {
    getSomething () {
     this.$emit('onitembind', 'I AM EMITTED FROM CHILD')
    }
  }
})

new Vue({
  el: '#app',
  data () {
  	return {
      item: false
    }
  },
  methods: {
    acceptDataFromChild(event) {
     	console.log('event:', event)
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
  <button @click='item = !item'> {{ item ? 'stop' : 'get' }} data from child </button>
  <my-component :item='item' @onitembind='acceptDataFromChild'></my-component>
</div>

You can check your console to see that every time the item prop changes to true an event will be emitted from child component and the parent catches it using acceptDataFromChild. The stop is redundant, as it only toggles the state of item to false. But this should work for your case

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.