【前端】pid2children iview tree json

<script>
  import inBody from '../inBody'
  export default {
    components:{
      inBody
    }

    ,data () {
      return {
        data2: [
          {title: 'parent 1'}
          ,{title: 'parent 1'}
        ]
        ,pidData:[
          {id:"1",pid:"0",title:"一级目录"}
          ,{id:"2",pid:"0",title:"又是一个一级目录"}
          ,{id:"3",pid:"1",title:"二级栏目"}
        ]
      }
    }
    ,methods:{
      pid2children:function(){

        let pidData2 = this.pidData //pidData就是pid数据
        //pidData2 === this.pidData ? console.info("true") : console.info("false")
        pidData2.forEach(el => {
          delete el.children //delete 删除数组 数组长度不变 特别适合 索引用
        })

        let map = {}
        pidData2.forEach(el => {
          map[el.id] = el // 循环data拿到所有的id
        })

        let arr = []
        pidData2.forEach(el => {
          let parent = map[el.pid] // 拿到所有的pid,如果为真,和id进行对比,如果pid===id,就说明是id的子集
          if (parent) {
            (parent.children || (parent.children = [])).push(el)
          } else { // 如果不是就是第一级,没有pid或者pid为0
            arr.push(el)
            console.log('arr', arr)
          }
        })


        return arr;
      }
    }
    ,mounted:function(){
      this.$nextTick(function () {
        // Code that will run only after the
        // entire view has been rendered
        //this.getData2()
      })

    }
  }
</script>

  

posted @ 2019-01-10 17:12  彭成刚  阅读(211)  评论(0编辑  收藏  举报