Vue3 v-if Directive
v-ifDirective is used for conditional rendering, deciding whether to render an element or template fragment based on the truthiness of the expression.
Basic Description
v-ifThe directive conditionally renders an element based on the truthiness of the bound expression. When the condition is true, the element is rendered into the DOM; when false, the element is not rendered.
- Expected Type: any
- Purpose: Conditional rendering; decides whether to render the element based on the truthiness of the expression. When the condition is false, no DOM is rendered.
Basic Usage
Example
<template>
<div>
<p v-if="isLoggedIn">Welcome back, user</p>
<p v-else>Please log in</p>
</div>
</template>
<script>
export default {
data() {
return { isLoggedIn: true }
}
}
</script>
<div>
<p v-if="isLoggedIn">Welcome back, user</p>
<p v-else>Please log in</p>
</div>
</template>
<script>
export default {
data() {
return { isLoggedIn: true }
}
}
</script>
Combining with v-else and v-else-if
v-if can be used together with v-else-if and v-else to form a conditional chain:
Example
<div v-if="status === 'loading'">Loading...</div>
<div v-else-if="status === 'error'">Loading failed</div>
<div v-else>Content: {{ data }}</div>
<div v-else-if="status === 'error'">Loading failed</div>
<div v-else>Content: {{ data }}</div>
Other Extensions
Vue3 Built-in Directives