首页 > 其他 > 详细

vue 递归组件的两种方法

时间:2021-02-12 08:18:03      阅读:87      评论:0      收藏:0      [点我收藏+]
app.vue
<template>
  <div>
    <list :data="data"></list>
    <hr/>
    <render :data="data"></render>
  </div>
</template>

<script>
import list from "./list.vue";
import render from "./render.vue";
export default {
  name: "App",
  components: {
    list,
    render
  },
  data() {
    return {
      data: [
        { id: 1, name: "1" },
        {
          id: 2,
          name: "2",
          children: [
            { id: 21, name: "21" ,children:[{ id: 211, name: "211" },{ id: 212, name: "212" }]},
            { id: 22, name: "22" }
          ],
        },
        {
          id: 3,
          name: "3",
          children: [
            { id: 31, name: "31" },
            { id: 32, name: "32" },
          ],
        },
        { id: 4, name: "4" },
        { id: 5, name: "5" },
      ],
    };
  },
};
</script>

<style lang="scss" scoped>
</style>

list.vue
<template>
 <ul>
   <li v-for="item in data" :key="item.id">
     {{item.name}}
     <list v-if="item.children" :data="item.children"></list>
   </li>
 </ul>
</template>

<script>
  export default {
    name:‘list‘,
    props:{
      data:{
        type:Array,
        default(){
          return []
        }
      }
    },
    
  }
</script>

<style lang="scss" scoped>

</style>


render.vue


<script>
export default {
  name: "Render",
  props: {
    data: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  render(h) {
    let items = [];
    if (this.data.length) {
      items = this.data.map((item) => {
        if (item.children) { 
          return h("li", [
            item.name,
            h("Render", {
              props: {
                data: item.children,
              },
            }
            ),
          ]
          );
        } else {
          return h("li", item.name);
        }
      });
    }
    return h("ul", items);
  },
};
</script>

<style lang="scss" scoped>
</style>

 

vue 递归组件的两种方法

原文:https://www.cnblogs.com/7c89/p/14398211.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!