Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion in Single File Components Vue.js 3

Tags:

vue.js

vuejs3

How to use recursive components in Vue3?

Using recursive components in Vue 3 like normal components causes error Cannot access before initialization

Tree.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>
like image 507
Michael Zelensky Avatar asked Jul 28 '26 10:07

Michael Zelensky


1 Answers

Documentation:

An SFC can implicitly refer to itself via its filename.

Component can be imported via its filename, but without listing in in the components setup object. However, it is enough to use the named component in the template without importing it.

Tree.vue:

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

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

    const hasChildren = someExitRecursionCondition();

    return {
      hasChildren
    }
  }
</script>
like image 189
Michael Zelensky Avatar answered Jul 31 '26 14:07

Michael Zelensky