vue 递归组件

递归组件应用在于 不确定有多少子集 而渲染需要调用自身模版不断渲染,最终达成所需的dom格式

由两个vue页面来演示递归组件

1.数据传入页 Mode


<template>
  <div>
    <my-trees :list="list"></my-trees>
  </div>
</template>
<script>
import myTrees  from './treeMenus'
export default {
  data(){
    return {
      list: [
        {
          name: '黄焖鸡米饭111111111',
          cList: [
            { name: '二级黄焖鸡' },
            {
              name: 'one chicken',
              cList: [
                { name: '三级黄焖鸡3333', cList: [{ name: '四级黄焖鸡' }] }
              ]
            }
          ]
        },
        {
          name: '2222222222',
          cList: [
            { name: '二级黄焖鸡' },
            {
              name: 'one chicken',
              cList: [
                { name: '三级黄焖鸡3333', cList: [{ name: '四级黄焖鸡' }] }
              ]
            }
          ]
        },
        {
          name: '黄焖鸡米饭33333333',
          cList: [
              { name: '二级黄焖鸡' }, 
              { name: 'one chicken' }
            ]
        }
      ]
    }
  },
  components: {
    myTrees 
  }
}
</script>

2.递归组件 treeMenus.vue

<template>
 
  <ul>
    <li v-for="(item,index) in list" :key="index">
      <p @click="changeStatus(index)">{{item.name}}</p>
      <!-- 递归组件 每次往下传入下一级的数据  scopesDefault[index]控制显隐-->
      <tree-menus v-if="scopesDefault[index]" :list="item.cList"></tree-menus>
    </li>
  </ul>
 
</template>
<script>
export default {
  name: 'treeMenus',
  props: {
    list: Array
  },
  data() {
    return {
      scopesDefault: [],
      scopes: []
    }
  },
  methods: {
    changeStatus(index) {
      if (this.scopesDefault[index] == true) {//控制下级显隐
        this.$set(this.scopesDefault, index, false)
      } else {
        this.$set(this.scopesDefault, index, this.scopes[index])
      }
    },
    scope() {//遍历数据
      this.list.forEach((item, index) => {//循环数据
        this.scopesDefault[index] = false
        if ('cList' in item) {//当前还有下级
          this.scopes[index] = true
        } else {//当前没有下级
          this.scopes[index] = false
        }
      })
    }
  },
  created() {
    this.scope()//初始化显示内容
  }
}
</script>

 <style>
  ul {
    margin-top: 50px;
    padding-left: 20px !important;
  }
</style>

转载于:https://www.cnblogs.com/yzyh/p/10430902.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值