7

With vue 2 I could simply just

import Vue from "vue"

and then do the following

if (!(myComponent instanceof Vue)) return

Is there a way to do it in Vue3?

1
  • Why would you do that? Commented Apr 5, 2021 at 12:37

2 Answers 2

6

It is not a very elegant solution but you can check if it has a render function.

if (!(myComponent && typeof myComponent.render  === 'function')) return
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that while this is a reliable way to check for traditional components, Vue3 simplified the declaration of Functional Components in a way that they are now basically no more than a simple Function. The check above is not able to detect such Components. Unfortunately it looks like there is really no way to detect these, other than attempting to use them as a Component (or calling them with mocked args as: (props, { slots, emit, attrs }) and see if they return a valid template string).
1

You can use the h() (hyperscript) function from Vue and check its type property:

import { h } from 'vue'

function isVueComponent(comp) {
  const vnode = h(comp)

  if (!vnode.type) {
    return false
  }

  // Check if it's just an HTML Element
  if (typeof vnode.type === 'string') {
    return false
  }

  // A component that has render or setup property
  if (vnode.type.setup || vnode.type.render) {
    return true
  }

  // Check if functional component
  // https://vuejs.org/guide/extras/render-function.html#functional-components
  if (vnode.type.emits || vnode.type.props) {
    return true
  }
}

The last condition is tricky since a function without the props and emits properties is counted as a functional component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.