0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vue3】コンポーネント全体をifで制御したかった

Posted at

方法

二重にしたら、コンポーネント全体をifで制御できました。

<script>
</script>

<template>
    <template v-if="hoge">
        trueの時だけ表示
    </template>
</template>

divを使いたく無い場面で、こんな書き方にしました。

失敗した方法

ルートの<template>に直接ifを書いたところ、falseでも表示されてしまいました。

<script>
</script>

<template v-if="hoge">
    falseでもtrueでも表示
</template>

仕様確認

SFC 構文仕様(https://ja.vuejs.org/api/sfc-spec)

各 *.vue ファイルは、<template>, <script>, <style> の 3 種類のトップレベル言語ブロックと、オプションで追加できるカスタムブロックから構成されます

と公式に記載があるのでよく考えたら当たり前なのですが、

<template v-if="hoge">
    trueの時だけ表示
</template>

というのは、<template>の中でしかできないみたいです。
トップレベルのtemplateブロックにifはつけられない。

成功した方法の二重しにた<template>は、それぞれの役割が違いました。

template 役割
外側のtemplate SFCファイルのコンポーネント定義のルートコンテナ
内側のtemplate 子要素をグループ化するコンテナ

補足

このような<template>の中に<template>をネストする書き方は、Vue2.7頃から許容されるようになったようです。

もっといい方法あるよ!とか、そこちがうよ〜という方はぜひ教えてください🙇

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?