2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【vue.js】 componentの中身(html)を親から子に送る【slotの使い方】

Posted at

#1部分の転送
まずは親コンポーネントの外観から

app.vue
<template>
  <div class="row">
    <div class="col-12 text-center">
      <app-component>
        <p>this is blue</p>
      </app-component>
    </div>
  </div>
</template>
<script>
import Comp from "./components/child.vue";
export default {
  components: {
    appComponent: Comp
  }
};
</script>

ここでタブの中子コンポーネントに贈りたいhtmlを書く。

(※ちなみにappComponentがapp-component担っているが、
htmlは大小文字を識別できないので大文字を-として互換性があるらしい)

<app-component>
   <p>this is blue</p>
</app-component>
child.vue
<template>
    <div>
        <slot></slot>
    </div>
</template>

以下のslotの部分で上のp要素を受け取っている。


<slot></slot>

#複数転送したいとき

app.vue
<template>
  <div class="row">
    <div class="col-12 text-center">
      <app-component>
        <p slot="slotfirst">this is blue</p>

        <div slot="slotsecond">
           <button class="hogehoge"></button>
        </div>
      </app-component>
    </div>
  </div>
</template>
<script>
import Comp from "./components/child.vue";
export default {
  components: {
    appComponent: Comp
  }
};
</script>

ポイントはここslot=""でslotの名前を決めている事がわかる

<p slot="slotfirst">this is blue</p>

<div slot="slotsecond">
     <button class="hogehoge"></button>
</div>

指定したslotはnameで呼び出せる

child.vue
<template>
    <div>
        <slot name="slotfirst"></slot>
        <slot name="slotsecond"></slot>
    </div>
</template>
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?