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?

More than 5 years have passed since last update.

Vue.jsの条件付きレンダリング(v-ifなど)まとめ

Posted at

v-if

条件を満たしている場合、描画されます。

<div id="app">
  <h1 v-if="visible">Text</h1>
  
  <!--templateタグ指定でもOK-->
  <template v-if="visible">
    <h1>Text1</h1>
    <h1>Text2</h1>
    <h1>Text3</h1>
  </template>
  
  <button @click="visible = !visible">
    {{ visible ? "表示してます" : "非表示です"}}
  </button>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
      visible: true
    }
  })
</script>

v-show

条件を満たしていない場合、display:noneをスタイルに追加します。
そのためtemplateタグでは使用できません。ですが初期描画は遅いですが、v-ifと比べて処理が発生するときのコストが低いです。

とても頻繁に、切り替える場合はv-showを使用しましょう。

<div id="app">
  <h1 v-show="visible">Text</h1>
  <button @click="visible = !visible">
    {{ visible ? "表示してます" : "非表示です"}}
  </button>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
      visible: true
    }
  })
</script>

v-else

条件を満たしていない場合、描画されます。
v-ifの直後でないと使用できません。

<div id="app">
  <p v-if="visible">OK!</p>
  <p v-else="visible">Not OK...</p>
  <button @click="visible = !visible">
    反転
  </button>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
      visible: true
    }
  })
</script>

v-else-if

ちょっと複雑な条件式を指定できます。
v-ifの直下でないと使用できません。

<div id="app">
  <p v-if="count == 0">カウント0</p>
  <p v-else-if="count >= 1 && count <= 5">カウント1以上かつ5以下</p>
  <p v-else>カウント6以上</p>
  <button @click="count += 1">
    +1
  </button>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
      count: 0
    }
  })
</script>
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?