vue · Vue.js Basics
What is the difference between v-show and v-if directives?
Answers
- v-if only renders the element to the DOM if the expression passes whereas v-show renders all elements to the DOM and then uses the CSS display property to show/hide elements based on expression.
- v-if supports v-else and v-else-if directives whereas v-show doesn't support else directives.
- v-if supports tab but v-show doesn't support.
- All of the above
Condition 1 is true
Condition 2 is true
Neither condition is true
```
## Understanding v-show Directive
On the other hand, the `v-show` directive, which doesn't support else directives, also controls an element's visibility. It inserts all elements into the DOM irrespective of the condition and then uses CSS' `display` property to hide or show the elements.
For instance:
```html
This div will be toggleable based on condition1
```
Unlike `v-if`, `v-show` keeps the element in the DOM, only changing its display based on the condition.
## Selecting Between v-if and v-show
`v-if` is a "real" conditional. It ensures that event listeners or child components inside the conditional block are properly destroyed and re-created during toggles. This means `v-if` is lazy and switches only on the basis of conditions. If the condition is false on initial render, it won't even do anything.
On the contrary, `v-show` is much simpler - the element will always be rendered and switched based only on CSS. This means `v-show` is not lazy and renders the element regardless of the initial condition.
In conclusion, it is best to use `v-if` if the condition is not likely to change at runtime as it has a high toggle cost. `v-show` is advisable if conditions are likely to change frequently at runtime due to its low-cost visibility toggle.