Vue.js Developer interview question · Most asked
v-if or v-show: what is the difference?
Summary
v-if adds and removes the element (and its component instances) from the DOM; v-show always renders it and toggles CSS display. v-if has a higher toggle cost but nothing is rendered when false; v-show has a higher initial cost but cheap toggling.
Longer Answer
Use v-show for things toggled often (tabs, dropdowns) and v-if for conditions that rarely change or when the hidden content is expensive or should not exist (permissions, lazy sections). v-if also resets the component's state each time it is shown, which can be a feature or a bug. v-show does not work on <template> and has no v-else.
Key Points
- v-if: conditional rendering.
- v-show: CSS display toggle.
- Frequent toggles: v-show.
- v-if resets component state.
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- What are composables, and why did they replace mixins?