0

I'm trying to call a function in the parent of a child.

I have created a component I can use on multiple pages in my Vue project, once the function has run I want to call a function on the parent.

I can achieve this by doing this.$parent.getLocations() - and it works.

However as this is a component I need getLocations() to be a variable this could be getPets() or getLunch() for example.

I am passing through 'Location' to the component so I can use that.

I have tried: '${this.$parent}.get${this.type}s()}' (this.type being Location) and this.$parent + ".get" + this.type +" s()

However neither trigger the function.

How do I make `getLocations a variable to run the function?

0

2 Answers 2

2

It's an anti pattern. The child of the parent should not know about the parent's function.

In the child:

this.$emit('needs-locations', { type: this.type })

In the parent:

<child @needs-locations="getLocations" :locations="locations">

getLocations(type) {
  api.then((locations) => this.locations = locations)
}

This will give you bidirectional communication without dependency.

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

Comments

1

First you emit an event from the child to the parent, and you pass a type to it.

this.$emit('runFunction', type)

Then handle the event:

<child-component @runFunction="handleRunFunction"/>

On the parent runFunction would look like this:

handleRunFunction(type) {
        switch (type) {
            case 'Location':
                getLocations();
            case 'Pets':
                getPets();
            default:
                break;
        }
    }

A normal if-else statement works equally well.

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.