vue递归组件的简单使用

一个关键问题是,递归组件怎么调用自身,这里关键在于组件的name属性,

在递归组件内,只要生命name属性,就可以直接调用组件自身!!

来个样例:

父组件:

<template>
  <div>
    <item :data="searchParams"></item>
  </div>
</template>

<script>
export default {
  components:{
    item:()=> import("./comp/item"),
  },
  data(){
    return{
      searchParams:{
        name:"第一层",
        level:"1",
        list:[
          {
            name:"第二层",
            level:"2-1",
            list:null,
          },
          {
            name:"第二层",
            level:"2-2",
            list:[
              {
                name:"第三层",
                level:"2-2-1",
                list:[
                  {
                    name:"第四层",
                    level:"2-2-1-1"
                  }
                ]
              }
            ]
          },
          {
            name:"第二层",
            level:"2-3",
            list:[
              {
                name:"第三层",
                level:"2-3-1",
                list:[
                  {
                    name:"第四层",
                    level:"2-3-1-1"
                  }
                ]
              }
            ]
          },
        ]
      }
    }
  }
}
</script>

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

子组件:

<template>
  <div class="item_wrap">
    <div class="item_name">{{data.name}}</div>
    <div class="item_level">{{data.level}}</div>
    <el-button @click="changeVal(data)">修改这个值</el-button>
    <el-button @click="addlist(data)">添加</el-button>
    <div v-if="data.list && isArray(data.list)">
      <ul 
        v-for="item in data.list" 
        :key="item.level"
        class="list_wrap">
        <item :data="item"></item>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name:"item",
  props:{
    data:{
      type:Object,
      default:null
    }
  },
  data(){
    return{

    }
  },
  methods: {
    isArray(val){
      return (val  instanceof Array);
    },
    changeVal(data){
      data.name = "啦啦啦"
    },
    addlist(data){
      if(data.list && this.isArray(data.list)){
        data.list.push({
          name:"嘤嘤嘤",
          level:new Date().getTime()
        })
      }
    }
  },
}
</script>

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

 

效果:

 

 

 

 

 

 

posted @ 2020-12-10 12:29  古墩古墩  Views(367)  Comments(0Edit  收藏  举报