javascript - 如何在 Vue 3 中以编程方式创建组件实例?

标签 javascript vue.js vuejs2 vue-component vuejs3

我有一个用于常见场景的 Vue 2 模式:以编程方式创建实例以在模板外部的动态内容上打开模态/对话框/灯箱。

在 Vue 2 中,我发现了这种模式:

// DialogService.js

export default {
  alert(text) {
    const DialogClass = Vue.extend(DialogComponentDef);
    let dialog = new DialogClass({ propsData: { text } });

    dialog.$on('close', () => {
      dialog.$destroy();
      dialog.$el.remove();
      dialog = null;
    });

    // mount the dynamic dialog component in the page
    const mountEl = document.createElement('div');
    document.body.appendChild(mountEl);
    dialog.$mount(mountEl);
  },
};

知道 Vue.extends$on$destroy 不再存在,我如何在 Vue 3 中实现这一点? 您可以通过 clicking here 查看 DialogService.js 的完整示例.

最佳答案

这里是如何在 Vue 3 中使用 createApp,但不会保留上下文(存储、插件、指令...)。

// DialogService.js
import { createApp } from 'vue';

export default {
  alert(text) {
    const mountEl = document.createElement('div');
    document.body.appendChild(mountEl);

    const dialog = createApp({ extends: DialogComponentDef }, {
      // props
      text,
      // events are passed as props here with on[EventName]
      onClose() {
        mountEl.parentNode.remvoeChild(mountEl);
        dialog.unmount();
        dialog = null;
      },
    });

    dialog.mount(mountEl);
  },
};

为了保持上下文,这里可以使用 hrender Vue 方法看到更复杂的内容:https://github.com/vuejs/vue-next/issues/2097#issuecomment-709860132

关于javascript - 如何在 Vue 3 中以编程方式创建组件实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69732406/

相关文章:

javascript - 组件的值未更新

javascript - 在过滤器方法中访问 vue 实例/数据

javascript - Jquery/AJAX 函数在 Change 事件上不起作用

javascript - Angular printjs : ERROR TypeError: Object(. ..) 不是函数

javascript - 为什么在 JS 中你不能在原型(prototype)上设置非函数

javascript - 将单个值转换为数组

javascript - 根据 Vue.js 中的特定项目值获取列表中的最后一个值

vue.js - 模块解析失败 : Unexpected character '@' while running yarn run storybook with vue-loader

vue.js - vuejs 将模型从父组件传递给子组件并允许突变

javascript - Nuxt/Vue.js - 基于 Prop 动态加载子组件