use cytoscape.js 和vue.js 动态组件的keep-alive 怎么结合使用?

How to use use cytoscape.js in combination with vue.js dynamic component's keep-alive?

我正在尝试使用 Vue.js 2.0 构建单页应用程序。该应用程序应该具有多种操作模式,我想使用 Vue.js 提供的 Vue.js dynamic component. Since the state of each mode should be preserved while switching between them, I decided to use the keep-alive 功能来实现。其中一种模式应该是使用 Cytoscape.js .

创建的网络视图

我的问题来了。当我第一次切换到网络时,网络已正确初始化,但来回切换后,网络视图冻结。 keep-alive 正常工作(据我所知)并带回 Cytoscape 实例和正确的 HTML 部分。不知何故,Cytoscape 实例和 HTML 部分之间的联系似乎丢失了,尽管我不明白如何以及为什么。

这是一个示例代码。

//sample data for network
var testElements = [
    { data: {id: 'a'} },
    { data: {id: 'b'} },
    { data: {
        id: 'ab',
        source: 'a',
        target: 'b' 
        }
    }
];
    
//Vue components
Vue.component('otherView', {
    template: '<div>This is another mode</div>'
});

Vue.component('network', {
    template: '<div id="container" class="cy"></div>',
    mounted: function () {
        cy1 = cytoscape({
            container: document.getElementById("container"),
            elements: testElements
        });
    }
});

//Vue dynamic component
var vm = new Vue({
    el: "#dynamic",
    data: {
        currentView: 'otherView'
    }
});
.cy {
    width: 500px;
    height: 500px;
    position: absolute;
    top: 100px;
    left: 10px;
}
<script src="https://rawgit.com/cytoscape/cytoscape.js/master/dist/cytoscape.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="dynamic" >
    <div id="selectorButton">
        <button id="button1" @click="currentView='otherView'">Other view</button>
        <button id="button2" @click="currentView='network'">Network</button>
    </div>

    <keep-alive>
        <component :is="currentView"></component>
    </keep-alive>

</div>

我无法完全理解你的问题,但你可以尝试将你在 network 组件的已安装 oroperty 中编写的代码转移到激活的 属性,如下所示

    Vue.component('network', {
        template: '<div id="container" class="cy"></div>',
        activated: function () {
            if(initial state){
                cy1 = cytoscape({
                    container: document.getElementById("container"),
                    elements: testElements
                });
            }

        }
    }); 

这可能会有所帮助,因为当一个组件保持活动状态时,挂载的挂钩只会在第一次进入组件时被调用一次,它不会在随后进入时再次调用而被激活当 kept-alive

时,每次进入组件时都会调用 hook

如果您删除了一个 Cytoscape 实例,您就破坏了它。要么确保 Vue 不会破坏你的 DOM 元素,要么每次从 JSON 创建一个新的 Cytoscape 实例:http://js.cytoscape.org/#cy.json