VUE组件生成菜单树

269 阅读1分钟

树组件

<template>
  <ul class="label-box">
      <li class="label-item" v-for="(label,index) of list" :key="index">
          <p class="label" :class="{open: currentId == label.id,allowopen: label.children.length>0}"
             @click="showChildrenLabel(label.id)" :data-id="`${label.id}`">{{label.name}}</p>
          <tree v-if="label.children.length>0" :list="label.children"></tree>
      </li>
  </ul>
</template>

<style scoped lang="scss">
    .label-box{
        padding-left: 30px;
        .label-item{
            line-height: 30px;
            .label{
                &:hover{
                    background-color: aliceblue;
                }
            }
            .label+.label-box{
                display: none;
            }
            .label.open+.label-box{
                display: block;
            }
        }
    }
</style>
<script>
  export default {
      name: "tree",
      props: [
          'list'
      ],
      data () {
          return {
              currentId: 0
          }
      },
      mounted () {
      },
      methods: {
          showChildrenLabel (id) {
              if(this.currentId == id){
                  this.currentId = -1
                  return
              }
              this.currentId = id
          }
      }
  }
</script>

父组件使用:

<template>
  <div id="app">
    <div class="app-roll-box">
        <div class="tree-box">
            <ul class="">
                <tree :list="list"></tree>
            </ul>
        </div>
    </div>
  </div>
</template>

export default {
  name: 'App',
  components: {
      tree
  },
  data () {
    return {
        list: [
            {
                id: '1',
                name: '一级菜单',
                children: [
                    {
                        id: '1-1',
                        name: '二级菜单1-1',
                        children: [
                            {
                                id: '1-1-1',
                                name: '三级菜单1-1-1',
                                children: []
                            },
                            {
                                id: '1-1-2',
                                name: '三级菜单1-1-2',
                                children: []
                            }
                        ]
                    },
                    {
                        id: '1-2',
                        name: '二级菜单1-2',
                        children: [
                            {
                                id: '1-2-1',
                                name: '三级菜单1-2-1',
                                children: []
                            },
                            {
                                id: '1-2-2',
                                name: '三级菜单1-2-2',
                                children: []
                            }
                        ]
                    }
                ]
            }
        ]
    }
  }
}
</script>