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 1 year has passed since last update.

[Vue3]条件分岐ざっくりまとめ

Posted at

概要

v-ifとv-showについてざっくりまとめる。

v-if

v-ifはjavascript等のプログラミング言語の条件分岐と同じくif、elseif、elseをディレクティブにしたもの。
v-if判定で対象とならないタグはレンダリングされない。
また、templateタグに条件分岐を付することでタグ階層が深くなることを避けることができる。

記法
v-if=" 条件" ...
v-else-if=" 条件" ...
v-else
App.vue
<script setup lang="ts">
import { computed } from "vue";

const randomNumber = computed(
	(): number => {
		return Math.round(Math.random() * 100);
	}
);
</script>

<template>
	<p>
		点数:{{ randomNumber }}<span v-if="randomNumber >= 80"></span>
		<span v-else-if="randomNumber >= 70"></span>
		<span v-else-if="randomNumber >= 60"></span>
		<template  v-else>
			<div>不可</div>
			<div>がんばれ</div>
		</template>	</p>
</template>
出力結果
~80
優
79~70
良
69~60
可
59~
不可
がんばれ

v-show

真偽値のみで判定を行うディレクティブ。
v-showでは常にレンダリングされstyle属性によって表示/非表示となる。
また、常にレンダリングされることからtemplateタグには使用できない。

レンダリング結果に付されるcss
style="display:none;"
App.vue
<script setup lang="ts">
import { ref } from "vue";

const check = ref(false);
</script>

<template>
	<div>
		<input type="checkbox" name="" id="" v-model="check">
	</div>
	<span v-show="check">
		条件に合致
	</span>
</template>
チェックON時のレンダリング結果
<span style> 条件に合致 </span>
チェックOFFのレンダリング結果
<span style="display: none;"> 条件に合致 </span>
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?