ブログの投稿ログ

2021年
9月
8月
7月
6月

Vueのslotタグについて

Vueコンポーネントを利用する上で覚えておきたいslotについて書いていきます。

でも

// Parent.vue

<template>
  // ひな型を作っていく
  <div class="wrap">
    <p class="head">
      // slotに名前を設定
      <slot name="top" />
    </p>
    <p class="content">
      // slotに名前を設定
      <slot name="mid" />
    </p>
  </div>
</template>
<script>
export default {
  name: "Parent",
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wrap {
  margin: auto;
  width: 200px;
  height: 240px;
  border-radius: 10px;
  box-shadow: 0 0 15px #eee;
}
.head {
  border-radius: 10px 10px 0 0;
  background: #eee;
}
.content {
  padding: 10px;
}
</style>

// Child.vue

<template>
  <div class="home">
    // importしたparentコンポーネントを出力
    <Parent>
      // slotタグで指定した名前を書く
      <template #top>aaaa</template>
      // slotタグで指定した名前を書く
      <template #mid>
        <dl>
          <dt>hoge</dt>
          <dd>fuga</dd>
        </dl>
      </template>
    </Parent>
  </div>
</template>

<script>
import Parent from "./Parent";
export default {
  name: "Child",
  components: {
    Parent,
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
dl {
  text-align: center;
  margin: auto;
}
dt {
  font-size: 18px;
  font-weight: 800;
}
dd {
  margin: auto;
}
</style>