1
votes

In Vue I have a main component that houses a child component which is loaded on the page with a button and the button triggers saveTaskComment(). This works perfectly, and I can get into the .finally portion of the child components function. HOwever, when it completes and gets to that point I want to make a call back to the parent component to call the method getInformation again. The way I have it right now that doesn't work so I guess $parent isn't correct in this case.

What do I need to do to get the method in teh childComponent to call the original function

mainComponent

methods: {
    getInformation() {
        this.$root.$emit('fetchCommentsEvent');
    },
}

childComponent

saveTaskComment() {

/*function completes and gets to this step fine*/

    .finally(() => {
        this.$parent.getInformation();
    });
}
2
I don't think you can. You should emit an event in finally back to the parent and have the parentComponent to call getInformation() when certain event was emitted. - josephting
How would I emit an event back to parent though? - Geoff_S

2 Answers

1
votes

To emit some method from a child component, you have to pass that method to the child.

MainComponent.vue:

<child-comp @getInformation="getInformation" />

ChildComponent.vue:

.finally(() => {
    this.$emit('getInformation')
});

and in case you want to pass some data to the parent method, you can do that by

this.$emit('getInformation', dataVariable)
1
votes

I've made a sample on CodeSandbox to illustrate what I said in the comment.

The key point to take away here is when you insert the Child's template into your Parent's template, you want to listen to certain event and call getInformation() when the event is emitted.

<Child @foo="getInformation()">This is child.</Child>

In order to emit this foo event back to the parent, you simply do this.$emit(eventName, optionalData) from the Child component.

Since we're listening for foo event, you want to emit it like so.

this.$emit("foo");