Call parent method with component

Tags: ,



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>

Answer

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".



Source: stackoverflow