getCurrentInstance in Vue 3

getCurrentInstance in Vue 3

Being developers we all used to work with this reference in programming. In Vue.js 2, this instance is available in option objects. We can access this inside the method, computed, watch and data. But when it comes to Vue.js 3 it is all about composition API. In the composition API we will be using setup to compose or organize our component business logics. Here, this will not be available inside the setup hook. Because the component is not created yet. To know more about setup function, you can refer Setup function in Composition API – Vue 3

So Vue.js 3 provides the getCurrentInstance function for us. Using getCurrentInstance, we can access component instance inside the setup hook. It will be available inside Lifecycle Hooks also. Let’s take a deep dive!.

getCurrentInstance in Vue 3

getCurrentInstance in Vue 3

In short, we can use getCurrentInstance to get component instances. This is the replacement of this in Vue.js 2. It will be very useful for custom Vue.js library authors and advanced developers for construction of complex components. Let me explain it with an example below.

Setup function Example

import { getCurrentInstance } from "vue";
export default {
  setup() {
    // accessible inside setup function
    const instance = getCurrentInstance();
    console.log(instance);
  },
};

Note that, getCurrentInstance won’t work outside of setup function and lifecycle hooks. If you want to access it call getCurrentInstance in the setup function and use the reference as follows,

import { getCurrentInstance } from "vue";
export default {
  setup() {
    // accessible inside setup function
    const instance = getCurrentInstance();
    
    const eventCallback = () => {
        getCurrentInstance(); // won't work here
        console.log(instance); // But you can use instance reference here
    }
    return {
        eventCallback
    }
  },
};

Lifecycle hook example

import { getCurrentInstance, onMounted, onUpdated, onUnmounted } from "vue";
export default {
  setup() {
    // Accessible in All lifecycle methods
    onMounted(() => {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("mounted!");
    });
    onUpdated(() => {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("updated!");
    });
    onUnmounted(() => {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("unmounted!");
    });
    return {};
  },
};

Note that, it will be accessible on composable function, when we call from setup function.

Real Time Example – getCurrentInstance Vue 3

Meanwhile, you may wonder why I need getCurrentInstance?. We can create a component using props, data and other Utilities. But when component logic increases or for a library creator, they need one component instance in another place. This is the case where we can use getCurrentInstance. Using getCurrentInsance we can access below things,

  • appContext.config.globalProperties – get the global properties
  • proxy – get the reactive proxy object of the component. By using this, we can change the reactive data
  • props – get all the props of component
  • emit – can be used to dispatch the events
  • vnode.el – the DOM element
  • refs – if ref is used in the child component, we can get all instance of child component using refs
  • and much more!. just console.log it, and we can see the same.

So in the below example, we are storing a proxy object reference with the help of getCurrentInstance. By using this object we can change respected component reactive data and invoke it’s methods.

 

Firstly in the Button.vue file we are storing a proxy object with the help of getCurrentInstance as follows.

// getCurrentInstance accessible on a composable function
// But it should be called inside setup function
const useBase = function (props) {
  onMounted(() => {
    let instance = getCurrentInstance();
    // Component instance stored in a global store.
    store.setInstance(props.id, instance.proxy);
  });
};

Secondly we are using store.js to store the getCurrentInstance proxy object as follows,

const store = {}
/**
 * A Global Store for component instances
 * Note that id should be unique
 */
export default {
    setInstance(id,proxy){
        store[id] = proxy;
    },
    getInstance(id){
        return store[id];
    }
}

Further, In the GetCurrentInstanceDemo.vue file, we get the stored proxy object of the button component using unique id. By using this reference, we can invoke it’s methods as follows,

const onMouseover = () => {
     // Here we can access Button component instance
    // And invoke it's methods using proxy object
     store.getInstance("btn").hide();
}
const onMouseleave = () => {
    store.getInstance("btn").show();
}

This is one of the use cases of getCurrentInstance. Likewise you can use it instead of this in Vue.js 2 based on your use cases.

Conclusion

In conclusion, getCurrentInstance is the special feature of Vue.js 3. We can use it instead of this in Composition API. By using it we can get a lot of utilities like emit, all props, data, proxy object, el DOM element.

Leave a Reply

%d bloggers like this: