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>
CodePudding user response:
You could provide only the component name option :
<template>
<Tree v-if="hasChildren" />
</template>
<script lang="ts">
export default defineComponent({
name:'Tree',
setup() {
const hasChildren = someExitRecursionCondition();
return {
hasChildren
}
}
</script>
CodePudding user response:
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>