【发布时间】:2021-12-12 09:01:18
【问题描述】:
我有一个用于常见场景的 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 的完整示例。
【问题讨论】:
-
其实一点关系都没有。事件总线不是这里的问题。
-
是的。您创建可以以编程方式使用的事件总线(on 和 emit 方法)。 Vue 3 没有提供这样的总线,所以需要外部提供。其余的可能是相同的,或多或少。 'new Vue' 被'createApp' 取代。不要把它看作是扩展组合,而是子应用程序,因为它确实是一个
-
好吧,createApp 不会保留前一个应用程序的上下文,而 Vue.extend 会保留,所以 createApp 无论如何都不是解决方案。我更改了标题,使其更加明确。
标签: javascript vue.js vuejs2 vue-component vuejs3