Categories
Vue Answers

How to call parent method with component with Vue.js?

Spread the love

Sometimes, we want to call parent method with component with Vue.js.

In this article, we’ll look at how to call parent method with component with Vue.js.

How to call parent method with component with Vue.js?

To call parent method with component with Vue.js, we can get the parent component’s method from the $parent property.

For instance, we write

<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();
      },
    },
  });

  const app = new Vue({
    el: "#app",
    methods: {
      someMethod() {
        console.log("parent");
      },
    },
  });
</script>

to define the child component with Vue.component.

In it, we add the someMethod method that calls this.$parent.someMethod.

this.$parent.someMethod is the parent component’s someMethod method.

Therefore, when we click the span, we see 'parent' logged.

Conclusion

To call parent method with component with Vue.js, we can get the parent component’s method from the $parent property.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.