Home > Software engineering >  How to get component instance in vue3's directive hooks?
How to get component instance in vue3's directive hooks?

Time:02-16

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?

CodePudding user response:

You could use the undocumented getCurrentInstance

example:

<script>
  import { getCurrentInstance, ref, onBeforeMount } from "vue";
  
  export default {
    setup() {
      // accessible inside setup function
      const instance = getCurrentInstance();
      console.log(instance); // available here

      onBeforeMount(() => {
        console.log(instance) // or here
      });

      return {}
    },
  };
</script>

Just be aware that it is undocumented for a reason. The communication around why it's undocumented and what alternative should be used is unclear (to me anyway), just know that it is an exposed internal function and some future vue version may remove it.

CodePudding user response:

The component instance is now under binding.instance:

const MyDirective = {
  beforeMount(el, binding, vnode) {                
  • Related