tezvyn:

Vue's v-if vs. v-show: When to Use Which

AI-drafted, machine-checkedSource: vuejs.orgbeginner

v-if adds or removes elements from the DOM; v-show just hides them with CSS. Use v-if for conditions that rarely change (like admin access) and v-show for frequent toggles (like a dropdown menu), as it has a lower toggle cost.

WHY IT EXISTS Web applications must dynamically show or hide content based on their state. Vue offers two approaches, v-if and v-show, to solve this problem, each optimized for a different performance trade-off: initial render cost versus the cost of toggling visibility later.

THE MENTAL MODEL Think of v-if as demolishing and rebuilding a room in your house. When the condition is false, the room doesn't exist. When true, you build it from scratch. v-show is like hanging a curtain in front of the room; the room is always there, taking up space, but you can quickly hide or reveal it.

HOW IT WORKS v-if is "real" conditional rendering. When its expression is false, the element and its children are completely removed from the DOM. They are only created and mounted when the condition becomes true. This makes v-if lazy—if the condition is initially false, nothing is rendered. In contrast, v-show always renders the element to the DOM on initial load. It then toggles visibility by changing the element's inline CSS display property. v-show does not support the <template> tag or work with v-else.

WHEN TO USE IT Use v-if if the condition is unlikely to change at runtime. This is ideal for one-time checks like user permissions, as you avoid the cost of rendering a block that will never be seen. Use v-show if you need to toggle something very frequently, like a modal or a custom dropdown. The higher initial render cost is paid once, but subsequent toggles are extremely cheap CSS changes.

WHEN NOT TO USE IT Avoid v-if for elements that are toggled often. The overhead of destroying and re-creating DOM elements, components, and event listeners on each toggle can harm performance. Avoid v-show for expensive components that are only needed in rare cases, as it will increase the initial page load cost by rendering them even if they start hidden.

ONE CANONICAL EXAMPLE To display a loading spinner while fetching data, v-if is the better choice. You might have Loading... and Content. The loading state is temporary and won't toggle back and forth rapidly. Once loading is complete, the spinner is removed from the DOM entirely, which is the desired behavior.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.