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-ifDirective: Thev-ifdirective is used to conditionally render an element. The element will only be rendered if the expression inside thev-ifevaluates 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-elseDirective: You can use thev-elsedirective in conjunction withv-ifto 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-ifDirective: You can also usev-else-iffor 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-showDirective: Thev-showdirective is another way to conditionally render elements. The difference is thatv-showtoggles the visibility of the element with CSS, whilev-ifactually 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