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

Total
3
Shares

I am trying to build a single page application using Vue.js 2.0. The application is supposed to feature multiple modes of operation, which I wanted to implement using Vue.js dynamic component. Since the state of each mode should be preserved while switching between them, I decided to use the keep-alive feature that Vue.js provides. One of the modes is supposed to be a network view created by using Cytoscape.js .

And here comes my problem. The network is initialized correctly when I switch the first time to it, but after switching back and forth, the network view freezes. keep-alive works properly (as far as I understand it) and brings back both the Cytoscape instance and the proper HTML section. Somehow, the connection between the Cytoscape instance and the HTML sections seems to be lost, although I don’t understand how and why.

Here is an example code.

_x000D_

_x000D_

//sample data for network_x000D_
var testElements = [_x000D_
    { data: {id: 'a'} },_x000D_
    { data: {id: 'b'} },_x000D_
    { data: {_x000D_
        id: 'ab',_x000D_
        source: 'a',_x000D_
        target: 'b' _x000D_
        }_x000D_
    }_x000D_
];_x000D_
    _x000D_
//Vue components_x000D_
Vue.component('otherView', {_x000D_
    template: '<div>This is another mode</div>'_x000D_
});_x000D_
_x000D_
Vue.component('network', {_x000D_
    template: '<div id="container" class="cy"></div>',_x000D_
    mounted: function () {_x000D_
        cy1 = cytoscape({_x000D_
            container: document.getElementById("container"),_x000D_
            elements: testElements_x000D_
        });_x000D_
    }_x000D_
});_x000D_
_x000D_
//Vue dynamic component_x000D_
var vm = new Vue({_x000D_
    el: "#dynamic",_x000D_
    data: {_x000D_
        currentView: 'otherView'_x000D_
    }_x000D_
});

_x000D_

.cy {_x000D_
    width: 500px;_x000D_
    height: 500px;_x000D_
    position: absolute;_x000D_
    top: 100px;_x000D_
    left: 10px;_x000D_
}

_x000D_

<script src="https://rawgit.com/cytoscape/cytoscape.js/master/dist/cytoscape.js"></script>_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
_x000D_
<div id="dynamic" >_x000D_
    <div id="selectorButton">_x000D_
        <button id="button1" @click="currentView='otherView'">Other view</button>_x000D_
        <button id="button2" @click="currentView='network'">Network</button>_x000D_
    </div>_x000D_
_x000D_
    <keep-alive>_x000D_
        <component :is="currentView"></component>_x000D_
    </keep-alive>_x000D_
_x000D_
</div>

_x000D_

_x000D_

_x000D_


Solution

If you remove a Cytoscape instance, you’ve destroyed it. Either make sure that Vue doesn’t destroy your DOM elements or create a new Cytoscape instance each time from JSON: http://js.cytoscape.org/#cy.json

Leave a Reply

Your email address will not be published. Required fields are marked *