我有一个用于常见场景的 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);
},
};
为了保持上下文,这里可以使用 h
和 render
Vue 方法看到更复杂的内容:https://github.com/vuejs/vue-next/issues/2097#issuecomment-709860132
关于javascript - 如何在 Vue 3 中以编程方式创建组件实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69732406/