This content originally appeared on DEV Community and was authored by CodeOzz
Welcome to the new vue academy ! It will be a list of lot of article on vue! I have 2.5 years of experience in this and I can teach a few thing about this !
With vue you can use some directives, today we will check the difference between v-show & v-if !
Basic
Both directives serve to display or hide a component, depending on the condition given.
But what is the difference?
The main difference is the living behavior !
v-if
The element will be removed from the DOM, so it will have a new lifecyle hooks ! ?
You can also use v-else-if and v-else
v-show
The element will remain in the DOM, v-show
will only use the display
property CSS to the element ! ?
So the element is not destroyed, so it will no have a new lifecyle hook !
Example
Take this code as example ?
Parent.vue
<template>
<div>
<button @click="changeState">
Switch state
</button>
<child v-show="isShowed" name="v-show" />
<child v-if="isLiving" name="v-if" />
</div>
</template>
<script>
import Vue from "vue"
import Child from "../child"
export default Vue.extend({
components: {
Child,
},
data() {
return {
isShowed: false,
isLiving: true,
}
},
methods: {
changeState() {
this.isShowed = !this.isShowed
this.isLiving = !this.isLiving
},
}
})
</script>
Child.vue
<template>
<div>
Hello from {{ name }}
</div>
</template>
<script>
import Vue from "vue"
export default Vue.extend({
props: {
name: String,
},
created() {
console.log(`Element named ${ this.name } is created`)
},
destroyed() {
console.log(`Element named ${ this.name } is destroyed`)
},
})
</script>
At init we have this console log :
Element named v-show is created
Element named v-if is created
When we change the state in order to activate directive :
Element named v-if is destroyed
Element named v-if is created
Element named v-if is destroyed
Element named v-if is created
Only v-if
component is reload and have a new cyclehook !
As mentioned above, we can check the display property
for v-show component
when component is hiding
<div style="display: none;">
Hello from v-show
</div>
Conclusion
Both is used to hide component, but the difference is the way of hiding this component !
v-if
- Element is removed from the DOM
- Element will have a new lifecyle hook
Can be use with
v-else-if
andv-else
Init load component is cheap
Toggle element is expensive
v-show
- Element remains in the DOM
- Element will not have a new lifecyle hook
Element will have
display: none
when set to falseInit load component is expensive
Toggle element is very cheap
This content originally appeared on DEV Community and was authored by CodeOzz

CodeOzz | Sciencx (2021-07-24T13:10:22+00:00) Vue Academy #3: v-show VS v-if. Retrieved from https://www.scien.cx/2021/07/24/vue-academy-3-v-show-vs-v-if/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.