“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
preface
I have learned the use of Vue3.0 reactive APIS and the source code of Reactive functions. This article will be followed by the previous one, which will combine single-step debugging and source code for exploration
Step through
Write a simple example
<body>
<div id="app">
<p>{{ state.counter }}</p>
</div>
<script>
const app = Vue.createApp({
setup() {
const state = Vue.reactive({
counter: 1
})
setInterval(() = > {
state.counter++
}, 1000)
Vue.watch(() = > state.counter, () = >{})return {
state
}
}
})
app.mount('#app')
</script>
</body>
Copy the code
- Open up debugging, first find
reactive
function/packages/reactivity/src/reactive.ts
.Step into theThe returnedcreateReactiveObject
function
- Single stepLooking at internal execution,
Proxy
The agent ofhandeler 是baseHandlers
, it is inreactive
Is passed in when called inmutableHandlers
- find
mutableHandlers
The location of the/packages/reactivity/src/baseHandlers.ts
Getter intercept
- One of the
get
是createGetter
Function, you can see it for the first timegetIn the data
- Looking at the call stack at this point, you can see that it was defined in the previous example
watch
Get data for the first time
- Single stepIf the data is not read-only
! isReadonly
Go to thetrack
Rely on the collection function, and thenStep into theLook at the internal execution
- Internally, a Map object that depends on the collection is generated
depsMap
According to the current datakey
From the globaltargetMap
I’m going to fetch, and if I didn’t find it the first time, I’m going to create a new valuedep
The collected dependencies are then executed to a dependency tracing functiontrackEffects
Will be current data dependenciesdep
The incoming
trackEffects
Determines if there is a component update function in the dependency, and if not, puts it in
- The getter is going to be executed several times, and once you collect the dependencies you can see what happens in the setter, you can cancel the breakpoint in the getter, okay
Setter intercept
- Set the break point at
createSetter
Function, you can see that the data has been rendered on the page, as in the examplesetInterval
Changed thecounter
So if you go to the setter, you get totrigger
Trigger the component update function
- Step into the
trigger
Let’s see, first we get the dependencies for the current data collectiondepsMap
Depending on the collectiondep
Put the component update function in
- Then go to the
triggerEffects
Triggering the actual build update function will collect the dependencies and do the corresponding operations
- Further down you can see that the page has also been updated
- The update process was introduced in the previous article about Vue3.0 source learning – update process analysis
Reactive Function execution flowchart
According to the source code analysis and single-step debugging can be simply organized a flow chart