tbowden
tbowden

Reputation: 1058

Add a variable to trigger a function in the parent - Vue

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?

Upvotes: 0

Views: 60

Answers (2)

ThibaultV
ThibaultV

Reputation: 81

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.

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50767

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.

Upvotes: 2

Related Questions