Vue3 Conditional Statements
Conditional Rendering
v-if
Conditional rendering uses the v-if directive, which displays the element only if the expression returns true:
v-if Directive
Using the v-if directive on an element:
<div id="app">
<p v-if="seen">Now you see me</p>
</div>
<script>
const app = {
data() {
return {
seen: true /* Changing to false will hide the message */
}
}
}
Vue.createApp(app).mount('#app')
</script>
Here, the v-if directive will determine whether to insert the <p>
element based on the value of the seen expression (true or false).
Since v-if is a directive, it must be added to an element. For multiple elements, you can wrap them in a <template>
element and use v-if on it. The final rendered result will not include the <template>
element.
v-if Directive
Using the v-if directive on a <template>
element:
<div id="app">
<template v-if="seen">
<h1>Website</h1>
<p>Google</p>
<p>tutorialpro</p>
<p>Taobao</p>
</template>
</div>
<script>
const app = {
data() {
return {
seen: true /* Changing to false will hide the message */
}
}
}
Vue.createApp(app).mount('#app')
</script>
v-else
You can use the v-else directive to add an "else" block to v-if:
v-else Directive
Generate a random number and determine if it is greater than 0.5, then output the corresponding message:
<div id="app">
<div v-if="Math.random() > 0.5">
Random number is greater than 0.5
</div>
<div v-else>
Random number is less than or equal to 0.5
</div>
</div>
<script>
Vue.createApp(app).mount('#app')
</script>
v-else-if
v-else-if serves as an else-if block for v-if and can be chained multiple times:
v-else Directive
Determine the value of the type variable:
<div id="app">
<div v-if="type === 'A'">
A
</div>
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<div v-else>
Not A/B/C
</div>
</div>
<script>
const app = {
data() {
return {
type: "C"
}
}
}
Vue.createApp(app).mount('#app')
</script>
>
v-else and v-else-if must follow v-if or v-else-if.
v-show
You can also use the v-show directive to display elements conditionally:
v-show Directive
<h1 v-show="ok">Hello!</h1>