Subscribe on changes!

Check whether a component is availble

avatar
Apr 5th 2022

I have searched related docs and places like stackoverflow but I can not find an answer.

What problem does this feature solve?

In some cases, a developer would like to check whether a custom component is gobal registered to:

  • Register a fallback if not exisit
  • Check if it is available and provide a backup content

For now, we could get infomation whether a component exist s in 2 ways:

  • Using app.component(ComponentName) to see check return value.

    This works good, but vue is not providing a way to get current app instance in docs, and I am not sure how can I get app inside a component

  • Using resolveComponent api

    This works, but it will output a warning saying Component xxx not exisit and can not be disabled.

What does the proposed API look like?

I hope I can get one of this:

  • a getApp composition api getting current app instance
  • a checkComponent or isComponentRegister api returning a boolean

Additional Context

I would be appearciate if someone point out a graceful way solveing this with current apis.

If so, I personally thinks that we may need some docs improvment here, as I really dig deep in to docs and not finding a possible solution with docs.

avatar
Apr 5th 2022

You can implement getApp() in userland with the inject/provide api:

app.provide('app', app)

function getApp() {
  return inject('app')
}

Then you can call app.component('ComponentName').

If you are registering global components, you usually already have access to the app since you need to call app.component(...), so you can also directly check.

avatar
Apr 5th 2022

Anyway, I found this useful, may help others if you are building a "middleware“ which do not have access to app, nor can not control component registing.

import { camelize, getCurrentInstance } from "vue";

export const isComponentRegistered = (name: string): boolean => {
  const instance = getCurrentInstance();

  return (
    typeof instance?.appContext.components === "object" &&
    camelize(name) in instance.appContext.components
  );
};

It must be called inside setup function to bind a instance.