如何结合使用cytoscape.js和vue.js动态组件的keep-alive?

PhJ*_*PhJ 5 cytoscape.js vue.js vuejs2

我正在尝试使用Vue.js 2.0构建单页应用程序。该应用程序应该具有多种操作模式,我想使用Vue.js 动态组件来实现。由于在切换每种模式时应保留每种模式的状态,因此我决定使用Vue.js提供的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'
    }
});
Run Code Online (Sandbox Code Playgroud)
.cy {
    width: 500px;
    height: 500px;
    position: absolute;
    top: 100px;
    left: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

max*_*anz 0

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