Vue.js provides several ways to perform conditional rendering, allowing you to display or hide elements based on certain conditions. Here are some common techniques for conditional rendering in Vue.js:
-
v-if
Directive: Thev-if
directive is used to conditionally render an element. The element will only be rendered if the expression inside thev-if
evaluates to true.<template>
<div>
<p v-if="isConditionTrue">This will be rendered if the condition is true.</p>
</div>
</template><script>
export default {
data() {
return {
isConditionTrue: true
};
}
};
</script>
-
v-else
Directive: You can use thev-else
directive in conjunction withv-if
to specify an alternative content to render when the condition is false.<template>
<div>
<p v-if="isConditionTrue">This will be rendered if the condition is true.</p>
<p v-else>This will be rendered if the condition is false.</p>
</div>
</template><script>
export default {
data() {
return {
isConditionTrue: false
};
}
};
</script>
-
v-else-if
Directive: You can also usev-else-if
for multiple conditional branches.<template>
<div>
<p v-if="condition === 'A'">Condition A</p>
<p v-else-if="condition === 'B'">Condition B</p>
<p v-else>Default Condition</p>
</div>
</template><script>
export default {
data() {
return {
condition: 'B'
};
}
};
</script>
-
Using
v-show
Directive: Thev-show
directive is another way to conditionally render elements. The difference is thatv-show
toggles the visibility of the element with CSS, whilev-if
actually adds or removes the element from the DOM.<template>
<div>
<p v-show="isConditionTrue">This will be shown if the condition is true.</p>
</div>
</template><script>
export default {
data() {
return {
isConditionTrue: true
};
}
};
</script>
Comments