BarryWalsh
BarryWalsh

Reputation: 1340

Vue.js 2 pass data from component to root instance

I have a component that makes an AJAX request. In the callback function I want to pass a value back to the parent or root instance.

So my callback function for example in the component is:

function callbackFunc(vm, response){
  vm.$emit('setValue', response.id);
}

and in my root instance I've tried using a method called setValue like this:

export default {
  name: 'app',
  data () {
    return {
      value : ''
    }
  },
  methods: {
    setValue: function(value){
      console.log(value);
    }
  }
}

This doesn't work. The documentation seems to say you need to have an event inside the template for it all to get hooked up but that's not going to work in this case.

Any ideas?

Cheers!

Upvotes: 0

Views: 1072

Answers (1)

Mark
Mark

Reputation: 92440

I'm using vue-router. So there's the root element that has an App component and then there'sthe component called Hello which has the ajax call

In the parent component's template you will have a <router-view><\router-view> which is where the vue-router will put your child. To wire everything up, you need to add the directive to the template:

<router-view v-on:setValue="parentMethod" ><\router-view> 

When the child calls $emit("setValue") after the ajax call, it will triggers parentMethod() on the parent. It's not clear why you say it won't work to hook it up in the template. Without the template, there's not really a parent/child relationship.

Upvotes: 1

Related Questions