How to Use v-if Without Rendering Extra DOM Elements in Vue.js
Recently, I needed a conditional element in my Vue.js application, so I used v-if
and v-else
in a <div>
.
<div v-if="condition">
something
</div>
<div v-else>
something else
</div>
However, I didn’t want to render out unnecessary elements to the DOM, and my styles didn’t work with these extra <div>
elements.
How could I write out this conditional without rendering new DOM elements?
Fortunately, Vue has the <template>
element, which won’t be rendered to the browser but will still parse through its contents and render out the HTML.
<template v-if="condition">
something
</template>
<template v-else>
something else
</template>