i am trying to understand the difference between onUpdated
and nextTick
. i created the below posted example.actually, i expected the text displayed inside onUpdated
for both of the 1st click and the 2nd click is to be the same, because as stated in the docs here
Registers a callback to be called after the component has updated its DOM tree due to a reactive state change
according to my understanding, the DOM-tree is the virtual DOM in which all the DOM nodes are to be updated first before these updates are applied on the actual DOM. the onupdated
will be called when the virtual DOM is updated and while the updates are not
yet reflected or applied on the the actual DOM. if we want to see the updates reflected on the actual DOM,nextTick
must be used
for the aforementioned reasons, i expected that the text in handleClick
, onBeforeUpdate
and onupdated
are to be the same.
please correct me if i misunderstood the difference between onUpdated
and nextTick
code:
<template>
<div>
<button @click="handleClick">Insert/Remove</button>
<div v-if="show" ref="content">I am an element</div>
</div>
</template>
<script setup>
import { reactive, ref} from 'vue'
import { onBeforeMount,onMounted,onUpdated,onBeforeUpdate } from 'vue'
const show = ref(true)
const content = ref()
const state = reactive({count: 0})
const handleClick = () => {
show.value = !show.value
console.log("handleClick:",show.value, content.value)
// nextTick(() => {
// // console.log(show.value, content.value)
// })
}
onMounted(()=>{
console.log("onMounted");
})
onBeforeUpdate(()=>{
console.log("onBeforeUpdate.show.value, content.value:",show.value, content.value)
})
onUpdated(()=>{
console.log("onUpdated.show.value, content.value:",show.value, content.value)
})
output
//after first click on Insert/Remove->handleClick
handleClick: false <div>I am an element</div>
App.vue:80 onBeforeUpdate.show.value, content.value: false <div>I am an element</div>
App.vue:83 onUpdated.show.value, content.value: false null
//after 2nd click on Insert/Remove->handleClick
handleClick: true null
App.vue:80 onBeforeUpdate.show.value, content.value: true null
App.vue:83 onUpdated.show.value, content.value: true <div>I am an element</div>