实例创建,实例挂载
- 在
新建test.html文件,内容如下:vue-3.2.30\packages\vue\examples\composition
<script src="../../dist/vue.global.js"></script>
<div id="demo">
<section>
<h1>{{count}}</h1>
</section>
</div>
<script>
const { createApp, ref } = Vue
var app = createApp({
setup() {
const count = ref(1)
return { count }
}
})
app.mount('#demo')
</script>
- 按住
,输入ctrl + p
,回车找到该文件runtime-core/src/apiCreateApp.ts
- 按住
,输入ctrl + f
,回车找到该文件位置,在浏览器中给该位置打断点function createApp(rootComponent
//用户执行了创建实例代码,其实是为了得到app实例对象,
//就是执行了一下函数createAppAPI内部返回的createApp方法,
//且返回app实例,app实例是一个对象,上面也挂载了mount等方法
var app = createApp({})
- 按住
,输入ctrl + f
,回车找到该文件位置,在浏览器中给该位置打断点const vnode = createVNode(
- 按住
,输入ctrl + f
,回车找到该文件位置,在浏览器中给该位置打断点render(vnode, rootContainer, isSVG)
// 当执行挂载方法 就会触发步骤4 和 步骤5的断点
app.mount('#demo')
- 按住
,输入ctrl + p
,回车找到该文件runtime-core/src/renderer.ts
- 按住
,输入ctrl + f
,回车找到该文件位置,按住createAppAPI(render, hydrate)
点击ctrl+左键
函数,找到render
函数的声明的位置render
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点patch(container._vnode
const render = (vnode, container, isSVG) => {// 首次vnode有值
if (vnode == null) {
if (container._vnode) {
unmount(container._vnode, null, null, true)
}
} else { // 首次container._vnode 没有值
patch(container._vnode || null, vnode, container, null, null, null, isSVG)
}
flushPostFlushCbs()
container._vnode = vnode // 首次container._vnode被赋值,供给下一次使用
}
- 按住
,点击ctrl + 左键
函数,找到patch
函数声明的位置patch
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点processElement(
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点processComponent(
- 只留步骤10 和 步骤11两个断点,刷新页面,点击
,可以看到patch的递归过程Resume script execution
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点,创建实例createComponentInstance(
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点,初始化工作执行setup,并且将结果响应式化setupComponent(instance)
- initProps
- initSlots
- setupStatefulComponent
- 按住
,输入ctrl + f
, 回车找到该文件位置,打上断点,setupRenderEffect(
- 按住
,输入ctrl + p
,回车找到该文件,runtime-core\src\component.ts
- 按住
,输入ctrl + f
,回车找到该文件位置,打上断点,将proxyRefs(setupResult)
函数执行的结果setup
,做代理,然后赋值给setupResult
浓缩版代码流程instance.setupState
const createApp = function(...args){
const app = ensureRenderer().createApp(...args)
const mount = app.mount
app.mount = function(v){
return mount(v)
}
return app
}
let renderer;
function ensureRenderer(){
return (renderer || renderer = createRenderer())
}
function createRenderer(){
return baseCreateRenderer()
}
function baseCreateRenderer(){
const render = (vnode,container,isSVG){
if(vnode == null){
if(container._vnode){
unmount(container._vnode,null,null,true)
} else{
patch(container._vnode || null,vnode,container,null,null,null,isSVG)
}
}
}
return {
render,
createApp:createAppAPI(render) // createApp()时,就会执行createAppAPI函数
}
}
function createAppAPI(render){
const context = createAppContext()
return function createApp(rootComponent,rootProps = null){ // createApp()时,返回app
const app = (context.app = {
mount(rootContainer){// 等到用户调用了app.mount()才会执行内部的mount函数
const vnode = createVNode(
rootComponent,
rootProps
)
render(vnode,rootContainer,isSVG)
}
})
return app
}
}
流程图
vue3源码流程图 | ProcessOn在线思维导图
vue3源码流程图 - ProcessOn