单文件组件中的递归 Vue.js 3

Mic*_*sky 4 vue.js vuejs3

如何在Vue3中使用递归组件?

在 Vue 3 中像普通组件一样使用递归组件会导致错误Cannot access before initialization

树.vue:

<template>
  <Tree v-if="hasChildren" />
</template>

<script lang="ts">
import Tree from './Tree.vue';

export default defineComponent({
  components: {
    Tree
  },

  setup() {

    const hasChildren = someExitRecursionCondition();

    return {
      hasChildren
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

Mic*_*sky 6

文档

SFC 可以通过其文件名隐式引用自身。

可以通过其文件名导入组件,但无需在components设置对象中列出。但是,在模板中使用命名组件就足够了,而无需导入它。

树.vue:

<template>
  <Tree v-if="hasChildren" />
</template>

<script lang="ts">
export default defineComponent({
  setup() {

    const hasChildren = someExitRecursionCondition();

    return {
      hasChildren
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)