xort
xort

Reputation: 347

VueJS - How to import sub-components only once in parent component

Let's say I have an App.vue file with the following

<template>
    <task-list>
        <task>Task 1</task>
        <task>Task 2</task>
    </task-list>
</template>
<script>
import TaskList from './tasklist.vue'
export default {
    //...
    components: {
        TaskList
    }
    //...
}
</script>

a TaskList.vue

<template>
    <ul>
        <slot></slot>
    </ul>
</template>
<script>
import Task from './task.vue'
export default {
    //...
    name: 'task-list'
    components: {
        Task
    }
    //...
}
</script>

a Task.vue

<template>
    <li><slot></slot></li>
</template>
<script>
export default {
    name: 'task',
    //...
}
</script>

and a main.js

import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

How do I import the sub-component Task.vue only once in TaskList.vue without also having to import it again in App.vue

It seems that if I do it this way, I get an error back from VueJS complaining about unregistered components

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

found in

---> at src/App.vue

Is there a way to indicate that task is a sub-component of task-list without global registration or importing again in App.vue?

Upvotes: 1

Views: 2972

Answers (2)

Volodymyr Symonenko
Volodymyr Symonenko

Reputation: 888

add a custom component task in App.vue:

<template>
  <task-list>
    <task>Task 1</task>
    <task>Task 2</task>
  </task-list>
</template>

<script>
import TaskList from './tasklist.vue'
import Task from './Task.vue'

export default {
    //...
    components: {
        TaskList,
        Task
    }
    //...
}
</script>

Upvotes: 1

Paul Tsai
Paul Tsai

Reputation: 1009

If you register Task in TaskList.vue,

then you can only use <task> in TaskList.vue's template.


Try this: App.vue use props to pass tasks (an array) to TaskList.vue

App.vue

<template>
    <task-list :tasks="tasks"></task-list>
</template>
<script>
import TaskList from "./tasklist.vue";
export default {
  //...
  data() {
    return {
      tasks: ['Task 1', 'Task 2']
    };
  },
  components: {
    TaskList
  },
  //...
};
</script>

TaskList.vue

<template>
  <ul>
    <task v-for="task in tasks" :key="task">{{ task }}</task>
  </ul>
</template>

<script>
import Task from './Task.vue';
export default {
  name: "task-list",
  props: {
    tasks: {
      type: Array,
      default: () => []
    }
  },
  components: {
    Task
  }
  //...
};
</script>

Full example app:

Edit Vue Template

Upvotes: 1

Related Questions