v-if/v-else
v-if adds an element to the page only when its condition is true, with v-else-if and v-else for alternatives.
In this page:
Syntax
<p v-if="condition">shown when true</p>
<p v-else-if="other_condition">other</p>
<p v-else>otherwise</p>
v-if/v-else
v-if renders or removes the element from the DOM based on a condition. v-else-if and v-else must directly follow. To toggle several elements at once, put v-if on a template tag.
Removing and creating elements has a cost, so use v-show for frequent toggling.
Note:
v-else must come immediately after a v-if or v-else-if element.
Example: v-if/v-else
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p v-if="score >= 90">Grade A</p>
<p v-else-if="score >= 75">Grade B</p>
<p v-else>Keep practising</p>
<template v-if="loggedIn">
<h3>Welcome back</h3>
<p>You have new mail.</p>
</template>
</div>
<script>
Vue.createApp({
data() { return { score: 82, loggedIn: true }; },
}).mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Grade BWelcome backYou have new mail.
-->
Live Example
Related Topics
Common Mistakes
- Placing other elements between v-if and v-else
- Using v-if and v-for together on one element
- Using v-if for rapid toggles
Chapter Summary
- v-if adds or removes elements
- v-else-if and v-else follow it
- template v-if groups elements
- Prefer v-show for frequent toggles
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: