Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Official definition:

A deferred callback is performed after the next Dom update loop ends. Use this method immediately after modifying the data to get the updated DOM.

Scene:

On passing parameters to child components; After we pass the parameters to the child component, we call a function in the child component to view the parameters.


<div id="app">
    <div class="msg">
        <form-report ref="child" :name="childName"></form-report>
    </div>
</div>
Vue.component('form-report', {
    props: ['name'].methods: {
        showName(){
            console.log('Subcomponent name:'+this.name)
        }
    },
    template: '<div>{{name}}</div>'
})
new Vue({
    el: '#app'.data: function(){
        return {
            childName: ' ',}},mounted(){
        this.childName = 'I am the child component name'
        this.$refs.child.showName()
    }
})

Copy the code

Although the name of the child component is displayed on the page, it is printed with an empty value:

When we try to look at the data immediately after assigning a value to it, we find that we can’t get it.

Have you ever wondered what happens when you run MSG =0 on a page and loop through MSG for 100 times? (Direct display 99)

Main principles:

Assignment is treated as an asynchronous operation in VUE, while viewing data is synchronous. Because of the event loop mechanism, we get old data every time. Check out vue’s official explanation:

In case you haven’t noticed, Vue executes asynchronously when updating the DOM. As long as it listens for data changes, Vue opens a queue and buffers all data changes that occur in the same event loop. If the same watcher is triggered more than once, it will only be pushed into the queue once. This removal of duplicate data while buffering is important to avoid unnecessary computation and DOM manipulation. Then, in the next event loop, “TICK,” Vue refreshes the queue and performs the actual (de-duplicated) work. Vue internally attempts to use native Promise.then, MutationObserver, and setImmediate for asynchronous queues, and setTimeout(fn, 0) instead if the execution environment does not support it.

So to manipulate the DOM after the data update operation, we can use vue.nexttick (callback) immediately after the data changes; This callback will be called after the DOM update is complete to retrieve the latest DOM element.

Nexttick (callback)

1. Put the callback into the callbacks to wait for execution; 2. Put the execution function into the micro task or macro task; 3. Events loop to microtasks or macro tasks, executing functions that in turn execute callbacks in callbacks.