简体   繁体   中英

How do I create a component instance programmatically in vue 3?

I need to create a vue 3 component instance programmatically. I'm trying to do so in a directive. I get the error, 'tooltip is not a constructor'.

Here is the relevant part of my directive code:

import tooltip from './tooltip.vue'; // component that I want an instance of

export const tooltipDirective = {
  beforeMount(el: any, binding: any, vnode: any) {
    ...
    const _tooltip = new tooltip(); // error - tooltip is not a constructor
    ...
  },
};

And here is my tooltip component (.vue file):

export default {
  name: 'tooltip',
  props: [
    'tooltipTxt',
    'tooltipPos',
  ],
  setup(props: any) {
    const lState: {isShowing: boolean} = reactive({
      isShowing: false
    });

    let positionClasses: string;
    switch (props.tooltipPos) {
      case tooltipPos.lt:
        positionClasses = 'right-1 bottom-1';
        break;
      case tooltipPos.rt:
        positionClasses = 'left-1 bottom-1';
        break;
      case tooltipPos.lb:
        positionClasses = 'right-1 top-1';
        break;
      default:
        positionClasses = 'left-1 top-1';
        break;
    }

    return {
      lState,
      props,
      positionClasses
    };
  }
};

The reason why it does not work is because your component has no real constructor or class. Therefore, you cannot create an instance of this component.

But there is a workaround for that.

const TooltipClass = Vue.extend(tooltip);
const tooltipInstance = new TooltipClass()

Vue.extend creates a subclass of the Vue constructor.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM