LoginSignup
1
1

More than 3 years have passed since last update.

【Vue.js】slotタグを使ってhtmlタグを親コンポーネントで定義し、子コンポーネントに渡す【slot】

Last updated at Posted at 2021-01-19

参考

Udemy参考動画:https://www.udemy.com/course/vue-js-complete-guide/
講師 : よしぴー(Yoshipi)さん

Vue.jsslotタグを使ってhtmlタグを親コンポーネントで定義する方法をご紹介します。

通常

子コンポーネント : ChildComponent

//ChildComponent

<template>
  <div>
    <p>{{ title }}</p>
  </div>
</template>


<script>
export default {
  data() {
    return {
      title,
    };
  }
};
</script>

親コンポーネント App.Vue

//App.Vue

<template>
  <div>
    <ChildComponent :title="タイトル"></ChildComponent>
  </div>
</template>

<script>
import ChildComponent from "./components/ChildComponent.vue";

export default {
  components: {
    ChildComponent,
  },  
};
</script>

結果

タイトル

プロパティを渡し、タグ子コンポーネントで定義する。

スロット

  • タグを親コンポーネント定義できる
  • 対応 : ver2.6.0~

子コンポーネント : ChildComponent

//ChildComponent

<template>
  <div>
    <slot></slot>
  </div>
</template>

親コンポーネント : App.Vue

//App.Vue

<template>
  <div>
    <ChildComponent>
    <template>
          <p>タイトル</p>
      <template>
    </ChildComponent>
  </div>
</template>

結果

タイトル

コンポーネント内のtemplateタグと子コンポーネントのslotタグが対応

デフォルト

slotの数だけtemplateが生成されるため、slotタグを複数置くと同じ内容が連続して表示される

デフォルトの仕様ということでフォールバックコンテンツと呼ばれる。

例えば、
子コンポーネント : ChildComponent

//ChildComponent

<template>
  <div>
    <slot></slot>
    <slot></slot>
    <slot></slot>
    <slot></slot>
  </div>
</template>

結果

タイトル
タイトル
タイトル
タイトル

スコープ

  • インスタンス内(親コンポーネント内)
  • CSSは例外 : 親コンポーネントのスタイルが優先的に働く

名前付きslot

  • slot : name属性(子コンポーネント)
  • template : v-slot(親コンポーネント)

nameの値とv-slotの引数が対応
注意:nameは、v-slotは引数

子コンポーネント : ChildComponent

//ChildComponent

<template>
  <div>
    <slot name="title"></slot>
    <slot name="name"></slot>
  </div>
</template>

親コンポーネント : App.Vue

//App.Vue

<template>
  <div>
    <ChildComponent>
    <template v-slot:title>
          <p>タイトル</p>
      <template>
      <template v-slot:name>
          <p>太郎</p>
      <template>
    </ChildComponent>
  </div>
</template>

結果

タイトル
太郎
1
1
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
1
1