7
3

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でReactの"this.children"的なやつ

Posted at

最近諸事情によりReactからVue.jsへ移行中です。
そこでReactで言うthis.children的なやつが
Vue.jsだとどう書くのか調べたのでメモします。

まずReactのChildrenってどんなやつか

超適当に

const ChildNode = props => (
  <h1>
    {props.children}
  </h1>
);

const ParentNode = () => (
  <ChildNode>
    Hello World
  </ChildNode>
);

↑のように書くと以下のHTMLになる

<h1>
  Hello World
</h1>

要素を決まった構造でラップしたいときや
渡された要素を特定の条件で表示切り替えしたいときに使っていました。
例) モーダルのコンポーネントなど

Vue.jsだとどう書くのか

スロットという機能を使うことで実現できるようです。
ドキュメントに丁寧な解説が有りました。

ChildNode
<h1>
  <slot>
    こんにちは 世界      
  </slot>
</h1>
ParentNode
<child-node>
  Hello World
</child-node>

出力結果は以下のようになります

<h1>
  Hello World
</h1>

もし<child-node>の中に何も設定されていない場合は
デフォルト値として「こんにちは 世界」が表示されます。

まとめ

Reactのchildrenと同じことはSlotを使えばできる。
さらにここでは紹介していませんが
名前付きスロットや、スコープ付きスロットなど便利な機能があるようです。
Vue.jsはドキュメントが充実しているので大変助かりました^^

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?