【Vue.js】slotを使って親コンポーネントからテンプレートを差し込む

はじめに

v-slotを使って親コンポーネントから子コンポーネントにテンプレートを差し込む方法について

コンポーネント

<template>
    <div class="row">
      <childComponent :tasks="todoTasks"
                taskListId="todo-list"
                @handleShowTaskDetailModal="handleShowTaskDetailModal">
        <template v-slot:header>       // v-slotで任意の名前を指定
          <div class="h4">TODO</div>  // この記述が差し込まれる
        </template>
      </childComponent>

      <childComponent :tasks="doingTasks"
                taskListId="doing-list"
                @handleShowTaskDetailModal="handleShowTaskDetailModal">
        <template v-slot:header>       // v-slotで任意の名前を指定
          <div class="h4">DOING</div>  // この記述が差し込まれる
        </template>
      </childComponent>

      <childComponent:tasks="doneTasks"
                taskListId="done-list"
                @handleShowTaskDetailModal="handleShowTaskDetailModal">
        <template v-slot:header>       // v-slotで任意の名前を指定
          <div class="h4">DONE</div>  // この記述が差し込まれる
        </template>
      </childComponent>
    </div>
</template>

コンポーネント

<template>
  <div class="col-12 col-lg-4">
    <div :id="taskListId" class="bg-light rounded shadow m-3 p-3">
      <slot name="header"></slot> // ここに差し込まれる
       // 親コンポーネントで指定した任意の名前を指定する
      <template v-for="task in tasks">
        <TaskItem :key="task.id" :task="task" @handleShowTaskDetailModal="$listeners['handleShowTaskDetailModal']" />
      </template>
    </div>
  </div>
</template>

上記のようにv-slotを使うことで、同じコンポーネントを呼びだしながら、部分的にテンプレートを変えることができる。