LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsについて学んだこと -slotについて-

Posted at

Vue.jsのslot機能についてまとめています。

slotとは

slotとは親となるコンポーネント側から、子のコンポーネントのテンプレートの一部を差し込む機能になります。

slotにはデフォルトslot、名前付きslot、スコープ付きslotなど、用途によって使い分けることができます。

名前付きslot

コンポーネント内にslotで置き換えたい箇所が複数ある場合は、名前付きslotを使います。

使用例:

<template>
  <div class="example">
    <slot name="hand"></slot>
  </div>
</template>
<template v-slot:hand>
  <h1>HAND</h1>
</template>

⇒表示結果

<template>
  <div class="example">
    <h1>HAND</h1>
  </div>
</template>

slotタグにname属性を付けることで、v-slot属性で呼び出したいslotの名前を定義することができる。
(slotに名前を付けない場合はデフォルトslotとして扱われる)

スコープ付きslot

子コンポーネントから親コンポーネントに対して、スロットコンテンツの定義に必要なデータを受け取ることが可能になります。

使用例:

[foo.vue]
<template>
  <div class="example2">
    <slot :text="text"></slot>
  </div>
</template>
<script>
export default {
  name: 'foo',
  data () {
    return {
      text: 'My name is foo'
    }
  }
}
</script>
<template>
  <div class="example2-1">
    <div v-slot:default="slotProps">
      <p>{{slotProps.text}}</p>
    </div>
  </div>
</template>
<script>
import foo from '../components/foo.vue'
export default {
  components: {
    foo
  }
}

⇒表示結果

<template>
  <div class="example2">
    <div>
      <p>My name is foo</p>
    </div>
  </div>
</template>
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