Interview questions:
created
How many page updates will be triggered if data is modified twice during the life cycle?
1. Synchronous
Let me give you a simple synchronization example:
new Vue({ el: "#app", template: `<div> <div>{{count}}</div> </div>`, data() { return { count: 1, } }, created() { = 2; = 3; }, });
existcreated
During the life cycle, = 2
and = 3
The way toReassign value.
The answer is thrown here directly: render once.
Why?
This is related to the responsive processing of data. Let’s first look at the logic of responsive processing:
export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { // Focus: Create a publisher instance const dep = new Dep() const property = (obj, key) if (property && === false) { return } // cater for pre-defined getter/setters const getter = property && const setter = property && if ((!getter || setter) && === 2) { val = obj[key] } let childOb = !shallow && observe(val) (obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? (obj) : val if () { // Focus: Collect the rendering watcher currently being calculated () if (childOb) { () if ((value)) { dependArray(value) } } } return value }, set: function reactiveSetter (newVal) { const value = getter ? (obj) : val /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (.NODE_ENV !== 'production' && customSetter) { customSetter() } // #7981: for accessor properties without setter if (getter && !setter) return if (setter) { (obj, newVal) } else { val = newVal } childOb = !shallow && observe(newVal) // Point: When the data changes, the publisher instance dep will notify the collected watcher for updates () } }) }
During the data responsive processing phase, a publisher is instantiateddep
, and passThe way to define the current data
get
andset
function. Generating virtualvNode
The stage will triggerget
The currently being calculated will be rendered in the functionWatcher
The collection, at this time, the publisherdep
ofsubs
There will be one more rendering in itWatcher
Example. When the data changes, it will triggerset
Function, notify publisherdep
middlesubs
In-housewatcher
Make updates.
As for how many updates will be triggered by the data modification, it will be with the current publisher.dep
ofsubs
Several renderings were collectedwatcher
It's relevant, please read it againwatcher
Collect andcreated
The order between executions:
._init = function (options) { // ... initState(vm); // ... callHook(vm, 'created'); // ... if (vm.$) { vm.$mount(vm.$); } }
We knowinitState(vm)
The data is responsively processed, but the publisher is nowdep
ofsubs
Or an empty array. When executedcallHook(vm, 'created')
When it is executed = 2
and = 3
The logic ofset
in the functionNotification collected
watcher
Make updates. However, at this timedep
ofsubs
It's an empty array, which is equivalent to doing nothing.
Only invm.$mount(vm.$)
During execution, generate virtualvNode
It will only be rendered whenWatcher
Collect, at this time,dep
ofsubs
Not empty. Finally, byvm.$mount(vm.$)
A rendering of the page was performed, but it was not because=2
or=3
And triggers unnecessary page updates.
In short, it iscreated
The execution of logic within the hook function is renderedwatcher
The collection was performed before, so the page update caused by data changes was not caused.
2. Asynchronous
After talking about the synchronization scenario, let’s give another asynchronous example:
new Vue({ el: "#app", template: `<div> <div>{{count}}</div> </div>`, data() { return { count: 1, } }, created() { setTimeout(() => { = 2; }, 0) setTimeout(() => { = 3; }, 0) }, });
existcreated
During the life cycle, it is executed asynchronously = 2
and = 3
The way toReassign value.
The answer is thrown here directly: render once for the first time, and the page is updated twice due to data changes.
Why?
This is witheventLoop
The event loop mechanism is related, we knowjavascript
is a single threaded language when we passnew Vue
During instantiation, the initialization method will be executedthis._init
Method, startVue
The underlying processing logic. When encounteringsetTimeout
During asynchronous operation, it will be pushed into the asynchronous queue and wait for the current synchronization task to be executed before the asynchronous queue is removed and the first element of the queue will be executed.
In the current example,initState(vm)
The data is processed responsively in stages. When executedcallHook(vm, 'created')
When it is = 2
and = 3
The logic is pushed into the asynchronous queue and waits for execution. Continue to executevm.$mount(vm.$)
During the process, virtual will be generatedvNode
, and then triggerget
Rendering of functionsWatcher
Collect, at this time,dep
ofsubs
There is a rendering in itwatcher
。
After the first page rendering is completed, it will be executed=2
The logic of data modification will triggerset
in the function, the publisher at this time
dep
ofsubs
Not empty will cause the page to be updated. Similarly,=3
It will cause the page data to be updated again. That is to say, the first rendering is because=2
and=3
It will also cause the page to be updated twice.
III. Additional
If I change the value anddata
What about the values defined in the same?
new Vue({ el: "#app", template: `<div> <div>{{count}}</div> </div>`, data() { return { count: 1, } }, created() { setTimeout(() => { = 1; }, 0) }, });
At this time, it is triggeringset
In the logic ofif (newVal === value || (newVal !== newVal && value !== value)) { return }
The logic will not be executed again, the data of the data in this scenario will not cause the page to be updated again.
Summarize
From the life cyclecreated
and the order of page rendering,trigger
get
andset
The mechanism of the function, andeventLoop
Start with the event loop mechanism and analyze itcreated
The problem of how many page updates will be triggered by the two data modifications will be much clearer.
The above is the detailed explanation of the two data modifications in the vue interview created that will trigger several page updates. For more information about the update of the vue created data modification page, please pay attention to my other related articles!