-
new Vue
的时候调用会调用_init
方法- 定义
$set
、$get
、$delete
、$watch
等方法 - 定义
$on
、$off
、$emit
、$off
等事件 - 定义
_update
、$forceUpdate
、$destroy
生命周期
源码位置:src\core\instance\index.jsfunction Vue (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options) }
- 定义
-
调用
$mount
进行页面的挂载 -
挂载的时候主要是通过
mountComponent
方法源码位置:src\platforms\web\runtime\index.js
// public mount method Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component { el = el && inBrowser ? query(el) : undefined // 渲染组件 return mountComponent(this, el, hydrating) }
-
定义
updateComponent
更新函数 -
执行
render
生成虚拟DOM
-
_update
将虚拟DOM
生成真实DOM
结构,并且渲染到页面中_update
主要功能是调用patch
,将vnode
转换为真实DOM
,并且更新到页面中源码位置:src\core\instance\lifecycle.js
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) { const vm: Component = this const prevEl = vm.$el const prevVnode = vm._vnode // 设置当前激活的作用域 const restoreActiveInstance = setActiveInstance(vm) vm._vnode = vnode // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render // 执行具体的挂载逻辑 vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */) } else { // updates vm.$el = vm.__patch__(prevVnode, vnode) } restoreActiveInstance() // update __vue__ reference if (prevEl) { prevEl.__vue__ = null } if (vm.$el) { vm.$el.__vue__ = vm } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }
面试官:vue实例挂载的过程
于 2022-04-20 14:14:14 首次发布
本文深入解析Vue.js实例的初始化过程,包括_$init_方法的调用,$set、$get、$delete、$watch等响应式属性的定义,以及事件方法$on、$off、$emit的实现。同时,详细介绍了组件的挂载流程,特别是$mount方法如何调用_moutComponent_进行页面渲染。此外,文章还探讨了_update_方法如何生成和更新虚拟DOM,确保组件的正确渲染。
摘要由CSDN通过智能技术生成