Vue 2.0源码分析-从入口开始

之前提到过 Vue.js 构建过程,在 web 应用下,一起来分析 Runtime + Compiler 构建出来的 Vue.js,它的入口是 src/platforms/web/entry-runtime-with-compiler.js:

import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'const idToTemplate = cached(id => {const el = query(id)return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {el = el && query(el)if (el === document.body || el === document.documentElement) {process.env.NODE_ENV !== 'production' && warn(`Do not mount Vue to <html> or <body> - mount to normal elements instead.`)return this}const options = this.$optionsif (!options.render) {let template = options.templateif (template) {if (typeof template === 'string') {if (template.charAt(0) === '#') {template = idToTemplate(template)if (process.env.NODE_ENV !== 'production' && !template) {warn(`Template element not found or is empty: ${options.template}`,this)}}} else if (template.nodeType) {template = template.innerHTML} else {if (process.env.NODE_ENV !== 'production') {warn('invalid template option:' + template, this)}return this}} else if (el) {template = getOuterHTML(el)}if (template) {if (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile')}const { render, staticRenderFns } = compileToFunctions(template, {shouldDecodeNewlines,shouldDecodeNewlinesForHref,delimiters: options.delimiters,comments: options.comments}, this)options.render = renderoptions.staticRenderFns = staticRenderFnsif (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile end')measure(`vue ${this._name} compile`, 'compile', 'compile end')}}}return mount.call(this, el, hydrating)
}function getOuterHTML(el: Element): string {if (el.outerHTML) {return el.outerHTML} else {const container = document.createElement('div')container.appendChild(el.cloneNode(true))return container.innerHTML}
}
Vue.compile = compileToFunctionsexport default Vue

那么,当我们的代码执行 import Vue from 'vue' 的时候,就是从这个入口执行代码来初始化 Vue, 那么 Vue 到底是什么,它是怎么初始化的,我们来一探究竟。

1. Vue 的入口

在这个入口 JS 的上方我们可以找到 Vue 的来源:import Vue from './runtime/index',我们先来看一下这块儿的实现,它定义在 src/platforms/web/runtime/index.js 中:

import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser, isChrome } from 'core/util/index'import {query,mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement
} from 'web/util/index'import { patch } from './patch'
import platformDirectives from './directives/index'
import platformComponents from './components/index'
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
Vue.prototype.__patch__ = inBrowser ? patch : noop
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {el = el && inBrowser ? query(el) : undefinedreturn mountComponent(this, el, hydrating)
}
export default Vue

这里关键的代码是 import Vue from 'core/index',之后的逻辑都是对 Vue 这个对象做一些扩展,可以先不用看,我们来看一下真正初始化 Vue 的地方,在 src/core/index.js 中:

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'
initGlobalAPI(Vue)
Object.defineProperty(Vue.prototype, '$isServer', {get: isServerRendering
})
Object.defineProperty(Vue.prototype, '$ssrContext', {get() {return this.$vnode && this.$vnode.ssrContext}
})
Object.defineProperty(Vue, 'FunctionalRenderContext', {value: FunctionalRenderContext
})
Vue.version = '__VERSION__'
export default Vue

这里有 2 处关键的代码,import Vue from './instance/index' 和 initGlobalAPI,即初始化全局 Vue API,我们先来看第一部分,在 src/core/instance/index.js 中。

2. Vue 的定义

import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'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)
}initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)export default Vue

在这里,我们终于看到了 Vue 的庐山真面目,它实际上就是一个用 Function 实现的类,我们只能通过 new Vue 去实例化它。

有些同学看到这不禁想问,为何 Vue 不用 ES6 的 Class 去实现呢?我们往后看这里有很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法(这里具体的细节会在之后的文章介绍,这里不展开),Vue 按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理,这种编程技巧也非常值得我们去学习。

3. initGlobalAPI

Vue.js 在整个初始化过程中,除了给它的原型 prototype 上扩展方法,还会给 Vue 这个对象本身扩展全局的静态方法,它的定义在 src/core/global-api/index.js 中:

export function initGlobalAPI(Vue: GlobalAPI) {// configconst configDef = {}configDef.get = () => configif (process.env.NODE_ENV !== 'production') {configDef.set = () => {warn('Do not replace the Vue.config object, set individual fields instead.')}}Object.defineProperty(Vue, 'config', configDef)// exposed util methods.// NOTE: these are not considered part of the public API - avoid relying on// them unless you are aware of the risk.Vue.util = {warn,extend,mergeOptions,defineReactive}Vue.set = setVue.delete = delVue.nextTick = nextTickVue.options = Object.create(null)ASSET_TYPES.forEach(type => {Vue.options[type + 's'] = Object.create(null)})// this is used to identify the "base" constructor to extend all plain-object// components with in Weex's multi-instance scenarios.Vue.options._base = Vueextend(Vue.options.components, builtInComponents)initUse(Vue)initMixin(Vue)initExtend(Vue)initAssetRegisters(Vue)
}

这里就是在 Vue 上扩展的一些全局方法的定义,Vue 官网中关于全局 API 都可以在这里找到,这里不会介绍细节,会在之后的章节我们具体介绍到某个 API 的时候会详细介绍。有一点要注意的是,Vue.util 暴露的方法最好不要依赖,因为它可能经常会发生变化,是不稳定的。

4. 总结

那么至此,Vue 的初始化过程基本介绍完毕。这一节的目的是让同学们对 Vue 是什么有一个直观的认识,它本质上就是一个用 Function 实现的 Class,然后它的原型 prototype 以及它本身都扩展了一系列的方法和属性,那么 Vue 能做什么,它是怎么做的,会在后面的章节一层层帮大家揭开 Vue 的神秘面纱。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/181276.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PyCharm简介与安装

pyCharm的作用 PyCharm是一种Python的集成开发环境&#xff0c;带有一整套可以帮助用户在使用Python语言开发时提高效率的工具 pyCharm的集成 pyCharm的分类 PyCharm的下载 网址&#xff1a;https://www.jetbrains.com/pycharm/download/#sectionwindows PyCharm的安装

Java源码中经常出现的for (;;) {}:理解无限循环

其他系列文章导航 Java基础合集 设计模式合集 多线程合集 分布式合集 ES合集 文章目录 其他系列文章导航 文章目录 前言 一、无限循环的原理 二、使用场景 2.1服务器端的消息监听&#xff1a; 2.2守护线程的执行&#xff1a; 三、总结 前言 我们平常都会去阅读Java的源…

LeetCode [中等]128. 最长连续序列

给定一个未排序的整数数组 nums &#xff0c;找出数字连续的最长序列&#xff08;不要求序列元素在原数组中连续&#xff09;的长度。 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 128. 最长连续序列 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 利…

大数据学习(26)-数据倾斜总结

&&大数据学习&& &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 承认自己的无知&#xff0c;乃是开启智慧的大门 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4dd;支持一下博主哦&#x1f91…

第五届全国高校计算机能力挑战赛-程序设计挑战赛(C语言模拟题)

1、已有定义“int a[10]{1,2},i0;”&#xff0c;下面语句中与“ a[i]a[i1],i;”等价的是()。 A. a[i]a[i1]; B. a[i]a[i]; C. a[i]a[i1]; D. i,a[i-1]a[i]; 2、两次运行下面的程序&#xff0c;如果从键盘上分别输入6和4&#xff0c;则输出结果是(&#xff09;。 A. 7和5 …

3D打印报价系统

一款3d打印报价系统不仅可以展示三维模型&#xff0c;还能自动计算模型的相关信息&#xff0c;如面积、体积和尺寸信息。 用户上传三维模型后&#xff0c;系统会自动为其生成一个报价页面。在这个页面上&#xff0c;用户可以看到他们模型的所有相关信息&#xff0c;包括面积、体…

常用的系统播放器——MediaPlayer生命周期

常用的系统播放器——MediaPlayer 状态图以及生命周期 Idle状态、End状态、Error状态 MediaPlayer创建实例或者调用reset&#xff08;&#xff09;后就处于Idle状态&#xff0c;即就绪。 任意时刻调用release&#xff08;&#xff09;就会进入End 当运行过程中出错&#xf…

鼎捷副总裁谢丽霞:从四大趋势来看,数智时代企业如何加速研发创新

目录 导读 01 研发创新 势不可挡 ① 从逆向设计走向正向设计 ② 从专业协助走向全面协同 ③ 从单点场景走向业务闭环 ④ 从知识管理走向知识工程 02 鼎捷雅典娜 数智驱动企业新未来 03 鼎捷PLM 赋能企业研发创新 导读 研发&#xff0c;企业长青的必备源动能。如何在…

孩子写作业用的护眼灯哪种好?适合考研的护眼台灯推荐

随着现在小孩子的近视率越来越高&#xff0c;全国中小学生近视比率占大多数&#xff0c;许多家长也开始为孩子的健康成长而担忧&#xff0c;这时很多家长就会选择护眼台灯来为孩子保驾护航。但面对市面上五花八门的台灯品牌&#xff0c;各式各样的台灯许多家长却乱了阵脚&#…

android viewpager 禁止滑动

android viewpager 禁止滑动 前言一、viewpager 禁止滑动是什么&#xff0c;有现成方法吗&#xff1f;二、使用setOnTouchListener三、使用自定义viewpager总结 前言 本文介绍了本人有一个相关的需求需要实现这一功能&#xff0c;在过程中发现自己之前没做过&#xff0c;然后记…

Linux-文件夹文件赋权、文件指定修改用户和用户组

Linux-文件夹文件赋权、文件指定修改用户和用户组 文件权限说明文件夹文件赋权chmod命令chmod示例以数字方式修改权限给指定目录赋权给当前目录的所有子文件夹和文件赋权 chown修改属主、属组 文件权限说明 文件或目录的权限位是由9个权限位来控制的&#xff0c;每三位一组&am…

服务器运行情况及线上排查问题常用命令

一、top命令 指令行&#xff1a; top返回&#xff1a; 返回分为两部分 &#xff08;一&#xff09;系统概览&#xff0c;见图知意 以下是几个需要注意的参数 1、load average&#xff1a; 系统负载&#xff0c;即任务队列的平均长度。三个数值分别为 1分钟、5分钟、15分…

MES系统数字化看板:生产过程透明化与优化

在当今的制造业中&#xff0c;实现生产过程的透明化和优化已成为企业持续发展的关键。MES系统&#xff08;制造执行系统&#xff09;作为实现这一目标的重要工具&#xff0c;其数字化看板功能在生产现场管理中发挥着越来越重要的作用。 一、MES系统的基本概念与功能 MES系统是…

分页实体类封装

请求实体 /*** author suran* description 分页实体* create 2023/11/29 9:31*/ public class PageQuery implements Serializable {private Integer pageNum 1;private Integer page 1;private Integer pageSize 20;public PageQuery() {}public static PageQuery of(int …

IP地址的最后一位不可以为0或255

说明 通常情况下&#xff0c;IP 地址的最后一位不能为 0 或 255。这是因为这些特定的 IP 地址有特殊用途。 IP 地址的最后一位为 0 通常用作网络地址&#xff0c;表示整个网络的起始地址。IP 地址的最后一位为 255 通常用作广播地址&#xff0c;用于将数据包发送到同一网络中…

Pod控制器简介,ReplicaSet、Deployment、HPA三种处理无状态pod应用的控制器介绍

目录 一.Pod控制器简介 二.ReplicaSet&#xff08;简写rs&#xff09; 1.简介 &#xff08;1&#xff09;主要功能 &#xff08;2&#xff09;rs较完整参数解释 2.创建和删除 &#xff08;1&#xff09;创建 &#xff08;2&#xff09;删除 3.扩容和缩容 &#xff08…

0基础学习VR全景平台篇第124篇:VR视频地拍补地 - PR软件教程

上课&#xff01;全体起立~ 大家好&#xff0c;欢迎观看蛙色官方系列全景摄影课程&#xff01; 嗨&#xff0c;大家好&#xff0c;今天我们来介绍【地拍VR视频补地】。 之前已经教给了大家如何处理航拍图片的补天和航天视频的补天&#xff0c;肯定有很多小伙伴也在好奇&…

三大录屏软件推荐,让你轻松录制屏幕

录屏软件的应用变得越来越广泛&#xff0c;无论是记录屏幕上的内容以方便日后查阅&#xff0c;还是与他人分享操作过程&#xff0c;录屏软件都发挥着重要作用。然而&#xff0c;市面上的录屏软件种类繁多&#xff0c;质量参差不齐。那有没有好用的录屏软件推荐呢&#xff1f;在…

吃火锅(Python)

题目描述 吃火锅 以上图片来自微信朋友圈&#xff1a;这种天气你有什么破事打电话给我基本没用。但是如果你说“吃火锅”&#xff0c;那就厉害了&#xff0c;我们的故事就开始了。 本题要求你实现一个程序&#xff0c;自动检查你朋友给你发来的信息里有没有 chi1 huo3 guo1。…

第二证券:机构密集调研消费电子、半导体产业链

据上海证券报记者核算&#xff0c;近一个月来&#xff0c;共有41家消费电子类公司和92家半导体公司&#xff08;核算标准&#xff1a;申万职业2021&#xff0c;下同&#xff09;发布出资者调研纪要。其间&#xff0c;有的公司款待了16个批次估计超200家安排&#xff0c;更有公司…