44
Vue Academy #3: v-show VS v-if
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 !
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 !
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
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 !
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>
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
I hope you like this reading!
π You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and MP me π
Or get it HERE
π MY NEWSLETTER
βοΈ You can SUPPORT MY WORKS π
πββοΈ You can follow me on π
π Twitter : https://twitter.com/code__oz
π¨βπ» Github: https://github.com/Code-Oz
And you can mark π this article!
44