今天咱們簡單瞭解下vue3.0的異步更新原理,瞭解一下effect,watchEffect的特色以及最主要queueFlush函數的實現(函數名字本意就是:排隊刷新)vue
import { effect, reactive } from './reactivity';
let state = reactive({ name: 'zf', age: 11 })
effect(() => {
console.log(state.name);
})
state.name = 'zf';
state.name = 'jw';
state.name = 'jg';
每次更新狀態,都會從新運行effect。若是要是effect中包含渲染邏輯,可能會致使屢次更新視圖。react
import { effect } from "./reactivity";
export function watchEffect(effect, options) {
return doWatch(effect, null, options);
}
let postFlushCbs = [];
function queuePostFlushCb(cb){
postFlushCbs(cb); // 將effect放到數組中進行刷新
queueFlush();
}
function doWatch(source, cb, options) { // 作watch
let getter;
if (isFunction(source)) {
getter = () => source();
}
let scheduler = (job) => queuePostFlushCb(job);
const runner = effect(getter,{ // 建立一個effect
lazy:true,
computed: true,
scheduler // 自定義scheduler
})
runner();
}
watchEffect也是effect,只是自定義了scheduler函數數組
let isFlushPending = false; // 是否正在等待刷新
let isFlushing = false; // 是否正在刷新
const p = Promise.resolve();
function nextTick(fn) {
return fn ? p.then(fn) : p
}
function flushPostFlushCbs(){
if(postFlushCbs.length){ // 隊列有值進行隊列刷新
const cbs = [...new Set(postFlushCbs)];
postFlushCbs.length = 0;
for(let i = 0; i < cbs.length;i++){
cbs[i]();
}
}
}
function flushJobs() {
isFlushPending = false; // 開始執行任務
isFlushing = true; // 正在刷新
flushPostFlushCbs(); // 刷新隊列
isFlushing = false; // 刷新完畢
}
function queueFlush() {
if (!isFlushPending && !isFlushing) {
isFlushPending = true;
nextTick(flushJobs); // 稍後刷新任務隊列
}
}
最近:nextTick本質原理就是個promise(微任務),這裏會將effect 暫存起來並進行去重以後執行。promise
vue.config.js的優化配置異步
vue3.0新特性初體驗(二)ide
- END -