David-Desmaisons / Vue.D3.tree

Vue component to display tree based on D3.js layout.
https://david-desmaisons.github.io/Vue.D3.tree/tree
MIT License
874 stars 136 forks source link

The tree is not displayed when fetching data from API #74

Open NoAbdulrahman opened 3 years ago

NoAbdulrahman commented 3 years ago

Hi. I'm trying to display the tree with data fetched from the API. The tree is shown very well when using the same data as static, but it is not shown when fetching it from the API. The "console.log" in created() function prints the data as JSON string which means the data is fetched successfully. I used the "props identifier" but still nothing is displayed. Here is my code if you could have a look The HTML part:

<tree :data="tree"  :identifier="getId"  node-text="title"  layoutType="horizontal"
       type="tree"   Duration="0"  style="width:600px; height:600px" ...>
</tree>

ProductTree.vue script:

export default Vue.extend({
  name: "ProductTree",
  components: {
       tree,
  },
  data() {    
      return {     
             tree:{}
    };},
async created(){
      let response = await Service.getProducts();
      this.tree = response.data.data;
      this.tree=this.prepareData(this.tree);
      console.log(this.tree);
},
methods: {
      prepareData(data){
       ...
       return data;
       },
       getId(node) {
       return node.id;
    }, });

In Products.vue, I have: <div> <ProductTree /> </div>

Am I missing anything?

David-Desmaisons commented 3 years ago
this.tree = response.data.data;
this.tree=this.prepareData(this.tree);

This looks suspiscious. Try:

this.tree=this.prepareData(response.data.data);
NoAbdulrahman commented 3 years ago

@David-Desmaisons Thanks David, I tried but still nothing is shown. Here is a sample of my data if you could have a look:

{
    "id": 0,
    "title": "Products",
    "children": [{
        "id": 1,
        "title": "Motivate up to down communication",
        "children": [{
            "id": 7,
            "title": "Ensure 100% of team members receive feedbacks quarterly"
        }, {
            "id": 8,
            "title": "Roll out anonymous feedback surveys from bottom to up quarterly"
        }]
    }, {
        "id": 2,
        "title": "Empower colleagues and thus improve products",
        "children": [{
            "id": 9,
            "title": "Track feedback from new sign-ups"
        }, {
            "id": 10,
            "title": "Schedule meetings of all department members every two weeks"
        }] 
    }]
}

To be specific, the small circle of the root is shown, only that circle, nothing else. I think the problem is not in the data itself but in binding the data, I couldn't figure out how to do it.

NoAbdulrahman commented 3 years ago

The problem is solved by adding v-if=“dataLoaded” on the tree component and set the dataLoaded property to true loading the data. Also, I had to use json object instead of json string.