vue 递归组件的创建和使用

92 阅读1分钟

使用name属性实现递归

使用组件的name属性CompSelf,插入到当前组建的虚拟DOM中,即可实现点击按钮,会生成一份新的组件,无限循环,代码如下:

<template>
  <div class="box">
    <button @click="clickFun">组件自调用</button>
    <CompSelf v-if="show"></CompSelf>
  </div>
</template>

<script>
  export default {

    name: 'CompSelf',

    data () {
      return {
        show: false
      }
    },

    methods: {
      clickFun(){
        this.show = true
      }
    }
  }
</script>

使用子组件实现递归

父级组件:

<template>
  <div class="box">
    <child :list-data="listData"></child>
  </div>
</template>

<script>
import child from "./child.vue";
export default {
  name: "ComSelf",
  data() {
    return {
      show: false,
      listData: [
        {
          id: "1",
          value: "something",
          children: [
            {
              id: "101",
              value: "something",
              children: [
                { id: "10101", value: "something" },
                { id: "10102", value: "something" },
              ],
            },
            {
              id: "102",
              value: "hahahah"
            }
          ],
        },
      ],
    };
  },
  components: {
    child,
  },
  methods: {
    clickFun() {
      this.show = true;
    },
  },
};
</script>

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

子组件:

<template>
  <div class="testBox">
    <div v-for="(item, index) in listData" :key="index">
      <h1>{{ item.id }}</h1>
      <child v-if="item.children" :list-data="item.children"></child>
    </div>
  </div>
</template>

<script>
export default {
  name: 'child',
  props: {
    listData: {
      type: Array,
      default: () => []
    },
  },
};
</script>

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