Vue实例创建和挂载的详细过程 |
1. Vue 实例创建和挂载的过程概述Vue 实例的挂载过程涉及多个关键步骤,包括创建实例、编译模板、初始化数据和事件绑定等 。它的核心流程大致如下:
2. 分析源码:Vue 实例的创建与挂载过程我们从 Vue 2.x 的源码分析 Vue 实例的挂载过程 。以下是大致的分析步骤 。 2.1 Vue 实例的构建函数首先,我们来看 Vue 的构建函数,它通常是通过 function 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); } 在构造函数中,调用了 2.2 Vue 的 _init 方法Vue.prototype._init = function (options) { const vm = this; vm._uid = uid$1++; // 生成唯一 ID vm._isVue = true; // 标记 Vue 实例 vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {} ); // 合并构造函数默认选项和用户传入的选项 vm._renderProxy = vm; // 渲染代理 vm._self = vm; // 指向自己 initLifecycle(vm); // 初始化生命周期 initEvents(vm); // 初始化事件 initRender(vm); // 初始化渲染 callHook(vm, 'beforeCreate'); // 调用生命周期钩子 beforeCreate initState(vm); // 初始化数据、计算属性等 initInjections(vm); // 处理依赖注入 callHook(vm, 'created'); // 调用生命周期钩子 created if (vm.$options.el) { vm.$mount(vm.$options.el); // 挂载实例 } };
2.3 Vue 的 $mount 方法挂载的核心方法是 Vue.prototype.$mount = function (el, hydrating) { el = el && query(el); // 如果传入了 el,进行选择并获取 DOM 元素 if (el === document.body || el === document.documentElement) { warn('Do not mount Vue to <html> or <body> - mount to normal elements instead.'); return; } const options = this.$options; if (!options.render) { let template = options.template; if (template) { if (typeof template === 'string') { // 编译模板 template = compileToFunctions(template, this); } } else if (el) { // 没有模板时,从 DOM 中获取内容作为模板 template = el.outerHTML; } options.render = template ? compileToFunctions(template, this) : createEmptyVNode; } return mountComponent(this, el, hydrating); };
2.4 mountComponent 方法
function mountComponent(vm, el, hydrating) { vm.$el = el; callHook(vm, 'beforeMount'); let updateComponent; // 这里通过 render 函数来渲染视图 updateComponent = function () { vm._update(vm._render(), hydrating); }; // 调用 Vue 的渲染函数,执行视图更新 new Watcher(vm, updateComponent, noop, { before: callHook.bind(vm, 'beforeUpdate') }, true); callHook(vm, 'mounted'); return vm; }
2.5 Vue 的 _update 方法
Vue.prototype._update = function (vnode, hydrating) { const vm = this; const prevEl = vm.$el; const prevVnode = vm._vnode; vm._vnode = vnode; if (!prevVnode) { // 初次渲染 vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */); } else { // 更新渲染 vm.$el = vm.__patch__(prevVnode, vnode); } // 更新生命周期钩子 callHook(vm, 'updated'); };
3. 总结 Vue 实例挂载的过程Vue 实例的挂载过程包含以下几个主要步骤:
通过以上分析,我们可以理解 Vue 实例挂载的完整过程,以及其中涉及的关键函数和生命周期钩子 。 到此这篇关于Vue实例创建和挂载的详细过程的文章就介绍到这了,更多相关Vue实例创建和挂载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持! |