- Getting Started
- The Vue Instance
- Data Binding Syntax
- Computed Properties
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Methods and Event Handling
- Form Input Bindings
- Reactivity in Depth
- Custom Directives
- Custom Filters
- Building Large-Scale Apps
- Comparison with Other Frameworks
In string templates, for example Handlebars, we would write a conditional block like this:
<!-- Handlebars template -->
In Vue.js, we use the
v-if directive to achieve the same:
It is also possible to add an “else” block with
v-if is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use
v-if on a
<template> element, which serves as an invisible wrapper. The final rendered result will not include the
Another option for conditionally displaying an element is the
v-show directive. The usage is largely the same:
The difference is that an element with
v-show will always be rendered and remain in the DOM;
v-show simply toggles the
display CSS property of the element.
v-show doesn’t support the
You can use the
v-else directive to indicate an “else block” for
<div v-if="Math.random() > 0.5">
v-else element must immediately follow the
v-show element - otherwise it will not be recognized.
v-if block is toggled, Vue.js will have to perform a partial compilation/teardown process, because the template content inside
v-if can also contain data bindings or child components.
v-if is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.
v-if is also lazy: if the condition is false on initial render, it will not do anything - partial compilation won’t start until the condition becomes true for the first time (and the compilation is subsequently cached).
v-show is much simpler - the element is always compiled and preserved, with just simple CSS-based toggling.
v-if has higher toggle costs while
v-show has higher initial render costs. So prefer
v-show if you need to toggle something very often, and prefer
v-if if the condition is unlikely to change at runtime.