Vue.js|スロット
Vue.jsのスロットの使い方の備忘録です。
スロットとは
複数のページで同じデザイン部品を使いたいとき、一つの子コンポーネントを使い回すことがよくありますが、スロットを使うとこの子コンポーネントの中に親コンポーネント側のコードを埋め込むことができます。
文字で説明しても分かりづらいので実際にコードを書いていきます。
スロットの使いかた
まず、ページのベースとなる親コンポーネントblue.vue
を用意します。
子コンポーネントCardContent.vue
をインポートしています。
注目ポイントは、<card-content>
タグの配下にもコードが書かれている点です。
// 親コンポーネント blue.vue <template> <div> <h1>BLUE</h1> <card-content class="card"> <p class="text"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p> <img class="photo" src="~/assets/blue.jpg"> </card-content> </div> </template> <script> import CardContent from '~/components/CardContent.vue' ... </script>
子コンポーネントCardContent.vue
のコードはこちらです。
注目ポイントは、<slot />
タグです。
// 子コンポーネント CardContent.vue <template> <div class="content"> <p class="title">Card Content</p> <div class="wrapper"> <slot /> </div> </div> </template>
blue.vue
をブラウザで見ると、このように表示されます。
図で構造を確認します。
親コンポーネントの中に子コンポーネントが描画され、子コンポーネントの中の<slot />
タグの部分に、親コンポーネントの<card-content>
タグ配下のコードが描画されます。
同じ子コンポーネントを使い回す
複数のページで子コンポーネントCardContent.vue
を使いつつ、子コンポーネントの<slot />
タグの部分を変えてみます。
親コンポーネントyellow.vue
を新しく作成します。
<card-content>
タグ配下を、最初に作ったblue.vue
とは違うコードにします。
// 親コンポーネント yellow.vue <template> <div> <h1>YELLOW</h1> <card-content class="card"> <p class="lead"> lead lead lead </p> <img class="photo" src="~/assets/yellow.jpg"> <p class="text"> text text text text text text text text text text text text text text text text text text text </p> </card-content> </div> </template> <script> import CardContent from '~/components/CardContent.vue' ... </script>
最初に作ったblue.vue
と今作ったyellow.vue
を見比べてみます。
同じ子コンポーネントを使いつつも、<slot />
タグのグレー背景の部分は別の内容になっています。
スロットを使うと、こういった微妙に内容の違うコンポーネントを一つにまとめることができます。