Home > Blockchain >  calling grandparent method from inside the grandchild component
calling grandparent method from inside the grandchild component

Time:08-31

i have 3 nested components

<GrandParent />
   <Parent />
       <Child />

i have a button in my Child component and on double click i would like to call a function in GrandParent component

 <button @dblclick="this.$parent.callGrandParentFunction(model)"> call grandparent </button>

using this.$parent i can only access Parent methods ... is there any way to go one level higher and call a GrandParent method ?

there is a similar question on SO but it's about vue2

VueJS Grandchild component call function in Great grandparent component

CodePudding user response:

Try to use provide/inject pattern :

GrandParent :

export default {
  methods: {
      someMethod(){
       //
      }
  },
  provide() {
    // use function syntax so that we can access `this`
    return {
      someMethod: this.someMethod
    }
  }
}

in GrandChild component :

export default {
  inject: ['someMethod'],
  created() {
    //run the method 
    this.someMethod()
  }
}

  • Related