0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

転職して、TypeScript、Vue.js、Nuxtを初めて使うようになり、slotについて調べたことを、備忘録兼アウトプットとしてまとめることにしました。少しでも誰かのお役に立てたら幸いです。

概要

Vue.jsのslot要素の説明と使い方について、サンプルコード付きでまとめました。

slot要素とは

slotはコンポーネントにカスタムコンテンツを挿入するためのプレースホルダーとして機能します。
親コンポーネントから子コンポーネントにコンテンツを動的に渡すために使用されます。コンポーネントを使用する際に、その中に挿入されるコンテンツを指定することができます。この場合、slotは、親コンポーネントが渡すどんなコンテンツでもこの位置に挿入されることを示します。

サンプルコードと解説

親コンポーネントから子コンポーネントに、テキストコンテンツを渡して挿入するサンプルコードを用意しました。

  • 親コンポーネント:AlertSample.vue
  • 子コンポーネント:AlertComponent.vue

サンプルコード

AlartComponentがSample.vueから以下のように利用されたとします

AlartComponent.vue
<template>
    <v-card >
        <v-card-text>
            <v-row>
                <v-icon>
                    mdi-alert-circle-outline
                </v-icon>
                <span><slot /></span>
            </v-row>
        </v-card-text>
    </v-card>
</template>
AlertSample.vue
<AlertComponent>
  この部分が警告メッセージとして表示されます。
</AlertComponent>

この場合、AlartComponent内のslotは、"この部分が警告メッセージとして表示されます。"というテキストで置き換えられます。つまり、最終的な出力は次のようになります。

<v-card>
  <v-card-text>
    <v-row>
      <v-icon>
        mdi-alert-circle-outline
      </v-icon>
      <span>この部分が警告メッセージとして表示されます。</span>
    </v-row>
  </v-card-text>
</v-card>

このようにして、コンポーネントの再利用性が高まり、さまざまなコンテンツを動的に表示することが可能になります。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?