[Vuejs]-How does axios get the tree json and render a vue page?

1👍

This is a data structure problem. You could reshape the Axios response into a data structure that facilitates rendering that particular tree:

  1. In a computed property (e.g., named "phoneGroups"), get all the groups, indicated by pid of 0:

    const groups = this.phoneList.filter(x => x.pid === 0);
    
  2. For each group, get the items belonging to that group, indicated by a pid that matches the group ID:

    const data = {};
    for (const g of groups) {
      const subitems = this.phoneList.filter(x => x.pid === g.id);
      data[g.id] = {
        group: g,
        subitems,
      };
    }
    return data;
    
  3. In the template, render the computed result as follows:

    <ul>
      <li v-for="({group, subitems}) in phoneGroups" :key="group.id">
        <span>{{group.name}}</span>
        <ol>
          <li v-for="subitem in subitems">-- {{subitem.name}}</li>
        </ol>
      </li>
    </ul>
    

demo

Leave a comment