guogangj
guogangj

Reputation: 2435

How to get component instance in vue3's directive hooks?

In Vue 2, I can get the component instance by vnode.componentInstance. However, there is no componentInstance in Vue 3's vnode. Vue 3's vnode has a component property. Unfortunately, I found it was null in my custom directive beforeMount hook. So, how do I get the component instance in Vue 3's directive hooks?

Upvotes: 1

Views: 3036

Answers (1)

tony19
tony19

Reputation: 138626

The component instance is now under binding.instance:

const MyDirective = {
  beforeMount(el, binding, vnode) {     👇
    console.log('component', binding.instance)
  }
}

demo

Normally, binding.instance would be the component instance (hence the name), but there seems to be a Vue bug that causes binding.instance to be the component definition instead.

Upvotes: 2

Related Questions