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>
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With