105

I have a component and want to add a click listener that runs a method in the parent template in Vue. Is this possible?

<template>
    <custom-element @click="someMethod"></custom-element>
</template>

<script>
    export default {
        name: 'template',
        methods: {
            someMethod: function() {
                console.log(true);
        }
    }
</script>
2
  • 1
    In the code you have posted, someMethod will be run when custom-element is clicked. Is that what you want or is there some other scenario?
    – Bert
    Commented Sep 14, 2017 at 0:20
  • 1
    Possible duplicate of Vue.js inheritance call parent method
    – thanksd
    Commented Sep 14, 2017 at 1:13

7 Answers 7

181

Yes!

It's possible to call a parent method from a child and it's very easy.

Each Vue component define the property $parent. From this property you can then call any method that exist in the parent.

Here is a JSFiddle that does it : https://jsfiddle.net/50qt9ce3/1/

<script src="https://unpkg.com/vue"></script>

<template id="child-template">
    <span @click="someMethod">Click me!</span>
</template>

<div id="app">
  <child></child>
</div>

<script>
Vue.component('child', {
  template: '#child-template',
  methods: {
    someMethod(){
        this.$parent.someMethod();
    }
    }
});

var app = new Vue({
    el: '#app',
  methods: {
    someMethod(){
        alert('parent');
    }
    }
});
</script>

Note: While it's not recommended to do this kind of thing when you are building disconnected reusable components, sometimes we are building related non-reusable component and in this case it's very handy.

7
  • 11
    this is no longer working for me, getting this.$parent.myMethod is not a function
    – raklos
    Commented Jan 23, 2020 at 21:21
  • 2
    @raklos It still work with the latest version of vue.js which is 2.6.11 at the moment. If it's not working for you, the problem is elsewhere. I would suggest to ask another question with the code you are using for help.
    – Gudradain
    Commented Jan 23, 2020 at 21:27
  • 11
    For those who get the "this.$parent.myMethod is not a function" error try this.$parent.$parent.myMethod or this.$parent.$parent.$parent.myMethod and so on. It may happen that your method is not in the direct parent but somewhere higher in the components hierarchy.
    – Ilyich
    Commented Mar 1, 2021 at 16:50
  • 2
    This solution is highly unreliable because it relies on the components hierarchy. It'll not work if you call the method from different components inside a template: <template id="child-template"> <!-- will work with this.$parent --> <span @click="someMethod">Click me!</span> <custom-component> <!-- will work with this.$parent.$parent --> <span @click="someMethod">Click me!</span> </custom-component> </template> (sorry I can't manage to format the code properly here)
    – migli
    Commented May 16, 2021 at 6:44
  • 1
    Provide/inject and props/emit are great tools for userland code, but when developing a library, you might not want to pollute your API by providing data to arbitrary descendants nor put the burdon on consumers to perform boilerplate event binding. A component communicating directly with its parent is only an antipattern when deployed in place of a more appropriate declarative idiom – sometimes code that smells bad will taste just fine. That said, $parent.$parent is a sinful temptation one must contemplate gravely before indulging. Commented Aug 22, 2021 at 19:05
59

Directly from the Vue.js documentation:

In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events...

So you need to emit a click event from your child component when something happens, which can then be used to call a method in your parent template.

If you don't want to explicitly emit an event from the child (using this.$emit('click') from your child component), you can also try to use a native click event, @click.native="someMethod".

39

Relying on calling this.$parent hides the dependency and will break when you use component libraries which create a longer child hierarchy

The prefered methods are to either:

  1. Explicitly pass methods as properties to child components (the same as passing data props)
  2. Or declare global methods as mixins

From nils's answer on Vue.js inheritance call parent method:

  1. Passing props (parent-child)

    var SomeComponentA = Vue.extend({
        methods: {
            someFunction: function () {
                // ClassA some stuff
            }
        }
    });
    
    var SomeComponentB = Vue.extend({
       props: [ 'someFunctionParent' ],
       methods: {
           someFunction: function () {
               // Do your stuff
               this.someFunctionParent();
           }
       }
    });
    

    and in the template of SomeComponentA:

    <some-component-b :someFunctionParent="someFunction"></some-component-b>
    
  2. Use Mixins

    If this is common functionality that you want to use in other places, using a mixin might be more idiomatic:

    var mixin = {
        methods: {
            someFunction: function() {
                // ...
            }
        }
    };
    var SomeComponentA = Vue.extend({
        mixins: [ mixin ],
        methods: {
        }
    });
    
    var SomeComponentB = Vue.extend({
       methods: {
           someFunctionExtended: function () {
               // Do your stuff
               this.someFunction();
           }
       }
    });
    

Further Reading

1
  • Number 1 is a great approach IMO. Best I've seen. I would have used Vuex for this but it would have been a lot of work to enable a modal.
    – errata
    Commented Jan 6, 2021 at 2:40
8

You can either pass the parent method down to the child component via props or you can get the child component to emit either a custom or native event.

Here's a Plunker to demonstrate both approaches.

0
6

In current vue version, this solution:
Passing props (parent-child)

var SomeComponentA = Vue.extend({
    methods: {
        someFunction: function () {
            // ClassA some stuff
        }
    }
});

var SomeComponentB = Vue.extend({
   props: [ 'someFunctionParent' ],
   methods: {
       someFunction: function () {
           // Do your stuff
           this.someFunctionParent();
       }
   }
});

The HTML part:

<some-component-b someFunctionParent="someFunction"></some-component-b>

Base on this post, should be modified in this way:

<some-component-b v-bind:someFunctionParent="someFunction"></some-component-b>
6

You can use $root like this with vanilla Vue, but, If you use nuxt with vue that response won't work. Why? because $root is nuxt itself. Let me show you an example:

this.$root.$children[1].myRootMethod()
  • $root: As I said before, this is nuxt.

  • $children[0]: this is nuxtloading.

  • $children[1]: this is your main component, in my case, it was a basic layout with a few global components and a global mixin.

  • $children[n]: other components on your app.

Hope it helps.

4
  • This works but kind of anti-pattern. It decreases readability. For similar case(anti-pattern) and looking better one is just to accessing the $parent to call the method. this.$parent.parentMethod()
    – Chase Choi
    Commented Jan 20, 2020 at 8:46
  • @ChaseChoi No, this doesn't work because my code is like an absolute path, it not depends on the children component because the result is always the same.
    – mrroot5
    Commented Jan 20, 2020 at 8:56
  • this.$parent.$options.methods.methodName(); Is the only thing that worked for me...
    – 3xCh1_23
    Commented Dec 23, 2020 at 21:09
  • Yes, this could work if you only have a parent component not a great grandfather or an unknown ammount of parent components.
    – mrroot5
    Commented Dec 28, 2020 at 13:56
3

Solution for Vue 3:

Another way to provide a function to a child component is to use provide/inject. The advantage is that you can avoid passing on props through multiple components, as inject can be used at any depth of child components.

Parent component:

<script setup>

import { provide } from 'vue'

myFunction(){
console.log('message from parent');
}

provide('message', myFunction);

Some child component:

<script setup>
import { inject } from 'vue'

const msg = inject('message')

//calling the injected function
msg()

</script>

Link to the docs.

2
  • How would this be implemented to use provide() and pass "someMethod" in the following example: export default { methods:{someMethod}}
    – Derek
    Commented Jul 22, 2023 at 15:23
  • On This link( vuejs.org/guide/components/provide-inject.html ) you can click on Options in the upper left corner to see examples for the Options API.
    – Stefan
    Commented Jul 27, 2023 at 11:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.