Vue组件实例化时对指令的处理

35 阅读1分钟

在某些情况下,我们需要在运行时动态创建并实例化 Vue 组件,例如根据用户输入或交互生成组件。本文将介绍如何使用 Vue 3 的 createAppcreateVNoderender 方法来动态实例化一个组件,并手动调用自定义指令的钩子函数。

import { createApp, h, createVNode, render } from 'vue';
function instantiateComponent(component, props) {
  const newComponent = defineComponent({ render: () => h(component, props) });
  const instance = createVNode(newComponent);
  render(instance, document.createElement('div'));
  // 手动调用自定义指令的钩子函数
  const directive = instance.component?.vnode?.dir;
  if (directive) {
    const { mounted, updated } = directive;
    if (mounted) {
      mounted(instance.el, directive.binding);
    }
    if (updated) {
      instance.component.update = function() {
        updated(instance.el, directive.binding);s
      };
    }
  }
  return instance.el;
}