'd3 graph rendering with vue

Because of non compatible dependencies, I have to downgrade from vue3 to vue2. I have created a force directed graph with D3 library. Everything worked find with vue3 using composition api. I am not familiar with vue 2 and adapting my graph to vue2 has not been working out for me. In vue3 it was very straitforward and ref() made it pretty easy to accomplish. As for vue2, I have tried making good use of lifecycle hooks such as computed and watch

Any help is more than welcome

Here is a minimalistic representation of my working component in vue3. This component creates the graph in a svg and then renders it in the template.

<template>
 <div class="col" style="position: absolute; width:100%; height:100%" >
     <div class="main-map-container" style="overflow: hidden; width: 100%;">
         <div ref="graph" class="canvas">
                
         </div>
     </div> 
 </div>
</template>

<script >
import {onMounted, onBeforeMount, ref} from 'vue'
export default {
setup(){

   const graph = ref() 
   const links = [{src:"Amazon",target:"Aurora"},{src:"Amazon",target:"Aurora"},{src:"Amazon",target:"Zoox"},{src:"Amazon",target:"Rivian"}]
   const nodes = [{id:"Amazon"},{id:"Aurora"},{id:"Zoox"},{id:"Rivian"}]


    onBeforeMount( async ()=>{
        const svgobj = ForceGraph(nodes, links)
        graph.value.appendChild(svgobj);
        })



    function ForceGraph(
    nodes, 
    links
    ){
   // The code for the graph has been removed since it is much too long
    return Object.assign( svg.node() );
    }


    return { graph }
    }
}
</script>
<style></style>

This is the vue2 component that i have emptied for this post



<template>
 <div class="col" style="position: absolute; width:100%; height:100%" >
     <div class="main-map-container" style="overflow: hidden; width: 100%;">
         <div ref="graph" class="canvas">
                
         </div>
     </div> 
 </div>
</template>

<script>
export default {

  setup(){
   
  },

methods: {

    },

watch: {

    },

props: {
      
    },

computed: {

    },

created() {

    },

mounted() {

    },

 updated(){
    
 },

 data() {
      return {
}}



}
</script>


<style>
</style>


Solution 1:[1]

You can use Vue3 composition API in vue 2. Install the composition api and then just keep your code the same, with the setup method exactly as it was.

The setup method, lifecycle hooks, and all the reactivity (refs and reactive objects) are made available to you, with very few incompatibilities.

We use d3 with Vue2 in this fashion all the time. 100% compatible.

https://github.com/vuejs/composition-api

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1