简体   繁体   中英

calling grandparent method from inside the grandchild component

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM