Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call parent method with component

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> 
like image 782
user2036108 Avatar asked Sep 14 '17 00:09

user2036108


People also ask

How do you call parent method from child component?

To call a parent component method from the child component, we need to pass the changeName() method as a prop to the child component and access it as a props data inside the child component.

How do you call a method in parent component from child component Vue?

To call a method in a child component with Vue. js, we can pass in a prop from the parent component to its child. Then in the child component, we watch the prop's value and run the method we want. in the child component to register the testProp prop and add the sayHello method.


1 Answers

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.

like image 59
Gudradain Avatar answered Oct 19 '22 23:10

Gudradain