programing

VueJs 반복 무한 v-for 루프

prostudy 2022. 8. 28. 12:02
반응형

VueJs 반복 무한 v-for 루프

저는 사용자 목록이 있는 계층 트리를 구축하려고 합니다. 각 계층 트리에 대해 "선배"를 설정하므로 누가 선임자인지 정의할 수 있습니다.이 문제를 해결하기 위해 다음과 같이 노력하고 있습니다.

여기에 이미지 설명 입력

이게 내가 하고 있는 일이야.

data(){
    return{
        users: [{
        id: 1,
        fname: 'Joe',
        lname: 'Smith',
        title: 'Super-Senior',
        senior_id: 0,
       }, {
        id: 2,
        fname: 'Bill',
        lname: 'Simons',
        title: 'Junior-1',
        senior_id: 0,
       }];
    }
},
methods: {
  juniors(senior) {
   return this.users.filter((user) =>
    user.senior_id == senior.id
   );
  }
}

다음으로 컴포넌트리를 나타냅니다.

<ul>
 <li v-for="chief in juniors(snr_chief)">
  <div class="child mx-1">{{chief.lname}} {{chief.fname}}<br /> <small>{{chief.title}}</small>
  </div>
  <ul>
   <li v-for="second in juniors(chief)">
    <div class="child mx-1">{{second.lname}} {{second.fname}}<br /> <small>{{second.title}}</small>
    </div>
    <ul>
     <li v-for="third in juniors(second)">
      <div class="child mx-1">{{third.lname}} {{third.fname}}<br /> <small>{{third.title}}</small>
      </div>
     </li>
    </ul>
   </li>
  </ul>
 </li>
</ul>

이것은 완벽하게 작동하지만, 물론 3단계까지 내려갑니다.사실 사용자가 몇 단계까지 내려갈 수 있는지 모릅니다.

그래서 재귀적인 컴포넌트를 갖는 것이 아이디어인데 어떻게 구현해야 할지 모르겠어요.예를 들어 다음과 같습니다.

<ul>
 <li v-for="chief in juniors(snr_chief)">
  <div class="child mx-1">{{chief.lname}} {{chief.fname}}<br /> <small>{{chief.title}}</small>
  </div>
  <Repeater :juniors="snr_chief" :self="chief" />
 </li>
</ul>

function listToTree(data, options) {
          options = options || {};
          var ID_KEY = options.idKey || 'Id';
          var PARENT_KEY = options.parentKey || 'ParentId';
          var CHILDREN_KEY = options.childrenKey || 'Items';

          var item, id, parentId;
          var map = {};
            for(var i = 0; i < data.length; i++ ) { // make cache
            if(data[i][ID_KEY]){
              map[data[i][ID_KEY]] = data[i];
              data[i][CHILDREN_KEY] = [];
            }
          }
          for (var i = 0; i < data.length; i++) {
            if(data[i][PARENT_KEY]) { // is a child
              if(map[data[i][PARENT_KEY]]) // for dirty data
              {
                map[data[i][PARENT_KEY]][CHILDREN_KEY].push(data[i]); // add child to parent
                data.splice( i, 1 ); // remove from root
                i--; // iterator correction
              } else {
                data[i][PARENT_KEY] = 0; // clean dirty data
              }
            }
          };
          return data;
        }
        
Vue.component('menu-tree', {
          props: ['item'],
          template: '<ul class="c-tree"><li>{{item.MenuName}}<menu-tree v-for="y in item.Items" v-bind:item="y"></menu-tree></li></ul>'
        })

        var app = new Vue({
            el:"#app",
            data:{
                items:[{
                    Id: 1,
                    MenuName: "Menu 1",
                    ParentId: null
                },
                {
                    Id: 2,
                    MenuName: "Menu 2",
                    ParentId: null
                },
                {
                    Id: 3,
                    MenuName: "Menu 3",
                    ParentId: null
                },
                {
                    Id: 4,
                    MenuName: "Sub Menu 1 - 1",
                    ParentId: 1
                },
                {
                    Id: 5,
                    MenuName: "Sub Menu 1 - 2",
                    ParentId: 1
                },
                {
                    Id: 6,
                    MenuName: "Sub Menu 1 - 1 - 1",
                    ParentId: 4
                },
                {
                    Id: 7,
                    MenuName: "Sub Menu 1 - 1 - 1 - 1",
                    ParentId: 6
                }],
                heirarchyItems: []
            },
            created: function(){
                this.heirarchyItems = listToTree(this.items);
            }
        });
.c-tree{
    list-style: none;
}
.c-tree > li {
    margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
    <menu-tree v-for="hItem in heirarchyItems" v-bind:item="hItem"></menu-tree>
</div>

언급URL : https://stackoverflow.com/questions/58191341/vuejs-recursive-infinite-v-for-loop

반응형