Talking about the implementation of Vue.NextTick

This is a source code resolution implemented after Event Loop and MicroTask.

Preheating, write a SLEEP function

 Function Sleep (MS) {RETURN New Promise (resolve => setTimeout (resolve , MS)} Async Function Onetick (MS) {Console.log ('start') AWAIT SLEEP (MS) Console.log ('end')} Oneicken (3000)   
Interpretation Sleep Function


The function execution is suspended when the ASYNC function is preused. We also know that this promisefn is executed in Microtask. When Microtask is not completed, the back Macrotask does not execute, we also implemented a SLEEP function through Microtask’s feature, blocking console.log execution


process


1 Execute Console.log (‘Start’)

2 Execute AWAIT execution pause, wait for the Promisefn after the AWAIT function to execute
3 In the SLEP function, the delay MS returns
4 Returns Return Resolve after executing console. Log (‘end’)

Method for how to use NexTke


VUE.NEXTTICK (() => {// Todo …}
   After the use method, look at the source code 

const nextTick = (function () {const callbacks = [] let pending = false let timerFunc // Timing function function nextTickHandler () {pending = false const copies = callbacks.slice (0) // copy callbacks.length = 0 // Clear for (let i = 0; i
{console. error (err)} Timerfunc = () => {p.Then (NEXTTICKHANDAL) .catch (logerror) // key}} else f ! isIE MutationObserver ‘) {var counter = 1 var observer = new MutationObserver (nextTickHandler) // key var textNode = document.createTextNode (string (conter)) observer.observe (textNode, {characterData: true}) timerFunc = () = > {counter + 1)% 2 TextNode.Data = string (counter)}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} else {Timerfunc = () =>{setTimeout (NEXTTICKHANDAL, 0) // Key}}} Return Function QueuenextTick (CB, CTX) {// API usage method Let _Resolve Callbacks.push (() => {if (cb) {Try {Cb.call (CTX )}} Catch (e) {Err}} else if (_resolve) {_resolve (ctx)}}) if (!:) {pending = true timerfunc ()} if (! cb && typeof prosise! == ‘undefined’) {RETURN New Promise ((resolve, reject) => {_Resolve = resolve})}}}) () // Self-execution function
    Gossure the source code can be understood To the NextTick API is a self-execution function 
Since it is a self-execution function, directly look at its return type, Return Function QueuenextTick (CB, CTX) {…}


Return Function QueuenextTick (CB, CTX) {// API usage method Let _Resolve Callbacks.push (() => {if (cb) {Try {cb.call (ctx)} catch e) {Err}} else if (_Resolve) {_Resolve (ctx)}}) f (! PENDING) {pending = true timerfunc ()} f (! cb&& typeof promise! == ‘undefined’) {Return New Promise ((Resolve) , REJECT) => {_Resolve = Resolve}}}
   only pays attention to the main process QueuenextTick function to incorporate us into () => {// Todo ... } Purked into Callbacks 

= ‘undefined’ && isnative (promise)) {var p = promise.resolve () var logerror = ERR => {Console.Error (ERR)} Timerfunc = () => {p.Then (nextTICKHANDLER) .catch (logerror) // focus}} else if (‘! isie mutationObserver’) {var counter = 1 var observer = New MutationOb Server // Key Var TextNode = Document.createTextNode (String (Conter) Observer.observe (TextNode, {Characterdata: true}) timerFunc = () => {counter = (counter + 1)% 2 textNode.data = String (counter)}} else {timerFunc = () => {setTimeout (nextTickHandler, 0) // Key} }
 This section we can see that the three points of the label indicate using Promise, MutationObserver or SetTimeout (FN, 0) in different browser environments   
Function nextTICKHANDLER () {pending = false const copies = callbacks.slice (0) // Copy Callbacks.Length = 0 // Clear for (Let i = 0; i

NextTickHandler is to put our previous Callbacks () => {// Todo …} Performed within the current task.
 Write a simple nexttick  < copies.length; i++) {
   copies[i]() // 逐个执行
  }
 }
 
Source code may be more rounded, we write a simple NextTick

const simplenextTick = (Function () {let Callbacks = [] Let Timerfunc Return Function QueuenextTick (CB) {Callbacks.push (()=> {// Push CLLBacks into CB () CB ()}) TimerFunc = () => {Return Promise.Resolve (). Then (() => {const fn = Callbacks.shift () Fn ()} }} TimerFunc () // Execute Timerfunc, return to a promise}}) () simplenext (() => {setTimeout (console.log, 3000, ‘nexttick’)})

We can see that NexTick’s principle is to return a promise, and our Todo’s code is executed in this promise. Now we can continue to simplify
   const simplenexttick = (function () {return function queuenexttick (cb) {Timerfunc = () => {Return Promise.resolve (). Timerfunc ()}}) () simplenext (() => {setTimeout (console.log, 3000, 'nexttick')}) 

is directly written.
 Const SimplenextTick = Function QueuenextTick (CB) {Timerfunc = () => {RETurn promise.resolve (). Then (() => {CB ()})} TimelFunc ()} simplenextTick (() => {setTimeout (console.log, 3000, 'nexttick')})   
This time we simplify the self-execution function

   
Const SimplenextTick = Function QueuenextTick (CB) {Return Promise.Resolve () .Then (cb)} simplenext (() => {setTimeout (console.log, 3000, ‘nexttick’)})

 Now we directly simplify to the end, now Discovering the core content of NexTick is Promise, a microtask.   Now we return to the NEXTTICK API official example 

{Message}}

var VM = New Vue ({EL : ‘#example’, Data: {Message: ‘123’}}) VM.MESSAGE = ‘new message’ // Change data VM. $ EL.TEXTCONTENT === ‘new message’ // falsevue.nexttick (function) ) {vm. $ el.textcontent === ‘new message’ // true}

  originalThe DOM update is to be executed after the next event is looped after the update of the data in the VUE. 
NEXTTICK's usage principle is mainly to resolve a single event update data.
Since we know that the nexttick core uses Microtasks, then we take a simplified next to the SLEEP function.
Const SimplenextTick = Function QueuenextTick (CB) {Return Promise.Resolve (). Then (CB)} SimplenextTick (() => {setTimeout (console.log, 3000 , ‘NEXTTICK’) / / can also be replaced with ajax request})


Function Sleep (MS) {RETURN New Promise (Resolve => setTimeout (resolve, ms) // can also be replaced with ajax request} async function onetick (ms) {console.log (‘start’) AWAIT SLEEP (MS) Console.log (‘end’)}} Ontick (3000)
   
We see that NEXTTICK and I write the execution result of the one -ton execution of the one. The difference is that next-pay is wrapped in a PROMISE to return and execute it, and OneTick is Execute a promise function with AWAIT, and this promise has its own WEBAPI function.
That is when using Ajax request, we use AXIOS directlyYou can return to Promise library
  async function getdata () {const data = AWAIT AXIOS.GET (URL) // Operation Data data to change Dom Return Data}  
This can also achieve the same role as NexTick

, and we can also see from the source code. MutationObserver can be used when the browser environment does not support Promise or SetTimeout (CB, 0) to achieve the same effect. But the ultimate core is Microtask

The above is all of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment