如何缓存动态实例化的Vue组件?

时间:2019-03-15 03:03:55

标签: vue.js vue-component

在我的应用程序中,我以编程方式实例化了一个对话框组件。该对话框可以(确实)包含一个子组件以显示内容。我是这样完成的:

// Create the containing dialog component.
// I don't care if this is cached or not, and it's easy
// to recreate.
//
var DialogComponent = Vue.extend(Dialog);
var instance = new DialogComponent({
    parent: parent,
    data: {...}
    propsData: {...}
});

// Compile the subcomponent string. In practice this would
// be built dynamically before being passed to
// Vue.compile()
// 
const template = '<ComponentName :binding="" ... />'
const x = Vue.compile(template);
const slotContent = {
    data() { return data},
    render: x.render,
    staticRenderFns: x.staticRenderFns
}

// Create a vnode from the compiled render functions. This
// is the part I am less confident in, as it appears the
// render function returned will always instantiate a new
// child component, and it feels like involving `instance`, 
// i.e. the dialog, is incorrect.
//
const vnode = instance.$createElement(slotContent);
instance.$slots.default = [ vnode ];

// Mount the dialog component to a DOM element. 
// 
var tmp = document.createElement('div');
document.body.appendChild(tmp);
instance.$mount(tmp);

// Hook the dialog close event to clean up the instance.
// In practice, when caching I would like to pull the
// child component out and only destroy the dialog instance.
// I can successfully set the child's vnode.data.keepAlive and
// persist the instance, but a new one gets created nonetheless.
// 
instance.$on('close', (e) => {
    instance.$el.parentNode.removeChild(instance.$el);
    instance.$destroy();
})

我相信这是实现此目标的公认方法,并且它可以完美地工作。但是,每次对话框消失时,当然都是$destroyed,并且再次显示该组件时,组件会重置。

我现在需要一种在对话框关闭并重新打开时维护子组件状态的方法。因此,想象一个对话框在创建时显示一个new Date(),在关闭并重新打开该对话框后,我需要显示相同的日期。我尝试了各种<keep-alive>的洒水,但无济于事,但我认为这不是该组件的适当用法。

成功缓存vnode避免了compile调用,但是因为(我认为)返回的render函数实例化了一个组件实例(在示例中为ComponentName),所以它不会重用原始的{{1} },即使我成功避免破坏它(ComponentName)。

最终,我认为我想在插入子组件时在vue / create-component.js中打line 73,但那里的断点永远不会被打(这可能是无关的webpack / source-maps东西) )。

是否有一种明智的方法来完成以编程方式实例化的Vue组件的缓存,以供以后重用,类似于vm._isDestroyed == false的工作方式?

0 个答案:

没有答案