vue源码分析(1)- 初始化

简介: vue 源码分析(1)- 初始化

hello 大家好,我是 superZidan,这篇文章想跟大家聊聊 vue源码分析(1)- 初始化 ,如果大家遇到任何问题,欢迎 联系我 或者直接微信添加 superZidan41

背景

Vue.js是现在国内比较火的前端框架,希望通过接下来的一系列文章,能够帮助大家更好的了解Vue.js的实现原理。本次分析的版本是Vue.js2.5.16。(持续更新中。。。)

目录

Vue.js的引入

这一章将会分析用户在引入Vue.js后,Vue框架做的初始化工作:创建Vue这个类,并往Vue类上添加类属性&类方法和实例属性&实例方法。

流程图:

vue(1)-p1.png

流程分析:

1)入口文件(platforms/web/entry-runtime-with-compiler.js)

  • 引入 platforms/web/runtime/index.js 得到Vue类
  • 缓存Vue的原型链上添加$mount方法,并重写该方法

2)platforms/web/runtime/index.js

  • 引入 core/index.js 得到Vue类
  • 往Vue类的config属性上添加mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement
  • 扩展Vue类options属性的directives,components
  • 给Vue类添加实例方法__patch__,$mount

3)core/index.js

  • 引入core/instance/index.js得到Vue类
  • 为Vue类添加添加全局API
  • 设置Vue实例属性$isServer,$ssrContext
  • 设置Vue类属性 FunctionalRenderContext
  • 添加Vue类的版本号

4)core/instance/index.js

  • 声明Vue类
  • 将Vue类传入各种初始化方法initMixin,stateMixin,eventsMixin,lifecycleMixin,renderMixin

源码分析:

我们将根据上述的流程分析从后往前分析,逐步分析Vue从定义到最后初始化结束的整个流程。

core/instance/index.js

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'

// 声明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)
}

// 将Vue类传入各种初始化方法

// 为Vue添加_init实例方法 Vue.prototype._init = function(){}
initMixin(Vue)

// 通过Object.defineProperty方法,添加vue的实例属性$data,$props,主要跟数据相关
// 添加Vue的实例方法 $set,$delete,$watch, eg:Vue.prototype.$set = function(){}
stateMixin(Vue)

// 添加Vue实例基础的事件方法
// 添加Vue实例方法 $on, $off, $emit, $once  eg:Vue.prototype.$on = function () {}
eventsMixin(Vue)

// 添加Vue实例生命周期的方法,主要涉及到组件的更新与销毁
// 添加Vue实例方法 $_update,$forceUpdate, $destroy
lifecycleMixin(Vue)

// 添加Vue实例方法 $nextTick, $_render以及_o,_n,_s,_l,_t等组件渲染相关的方法
renderMixin(Vue)

export default Vue

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'

// 为Vue添加类方法
// 通过Object.defineProperty方法添加Vue.config属性,
// 添加Vue.util,Vue.set,Vue.delelt,Vue.delete,Vue.nextTick,Vue.options
// 添加Vue.options上的'components','directives','filters'方法
// 实现Vue.options.components => 内建组件{keep-alive} => Vue.options.components.KeepAlive = xxxx
// 添加Vue.options上的_base属性
// 添加Vue.use,用于VUe插件的安装
// 添加Vue.mixin
// 添加Vue.extend,用于类的继承
// 添加Vue类上'component','directive','filter'方法

initGlobalAPI(Vue)

Object.defineProperty(Vue.prototype, '$isServer', {
   
  get: isServerRendering
})

Object.defineProperty(Vue.prototype, '$ssrContext', {
   
  get () {
   
    /* istanbul ignore next */
    return this.{
   mathJaxContainer[8]}vnode.ssrContext
  }
})

// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
   
  value: FunctionalRenderContext
})

Vue.version = '__VERSION__'

export default Vue

platforms/web/runtime/index.js

/* @flow */

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,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement方法
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// 实现Vue.options上的directives,components方法
// Vue.options.directives的model,show
// Vue.options.components的Transition,TransitionGroup方法
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
// Vue实例上的__patch__方法
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
// Vue实例上的$mount方法
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
   
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

// devtools global hook
/* istanbul ignore next */
if (inBrowser) {
   
  setTimeout(() => {
   
    if (config.devtools) {
   
      if (devtools) {
   
        devtools.emit('init', Vue)
      } else if (
        process.env.NODE_ENV !== 'production' &&
        process.env.NODE_ENV !== 'test' &&
        isChrome
      ) {
   
        console[console.info ? 'info' : 'log'](
          'Download the Vue Devtools extension for a better development experience:\n' +
          'https://github.com/vuejs/vue-devtools'
        )
      }
    }
    if (process.env.NODE_ENV !== 'production' &&
      process.env.NODE_ENV !== 'test' &&
      config.productionTip !== false &&
      typeof console !== 'undefined'
    ) {
   
      console[console.info ? 'info' : 'log'](
        `You are running Vue in development mode.\n` +
        `Make sure to turn on production mode when deploying for production.\n` +
        `See more tips at https://vuejs.org/guide/deployment.html`
      )
    }
  }, 0)
}

export default Vue

platforms/web/entry-runtime-with-compiler.js

/* @flow */

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'

// 实现通过id来缓存模板的功能。
const idToTemplate = cached(id => {
   
  const el = query(id)
  return el && el.innerHTML
})
// 缓存mount方法
const mount = Vue.prototype.$mount
// 重新实现Vue实例上的$mount方法
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
   
  el = el && query(el)

  /* istanbul ignore if */
  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.$options
  // resolve template/el and convert to render function
  if (!options.render) {
   
    let template = options.template
    if (template) {
   
      if (typeof template === 'string') {
   
        if (template.charAt(0) === '#') {
   
          template = idToTemplate(template)
          /* istanbul ignore if */
          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) {
   
      /* istanbul ignore if */
      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 = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (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)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
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方法
Vue.compile = compileToFunctions

export default Vue

以上就是引入Vue.js之后整个初始化过程。

目录
相关文章
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
1063 2
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
931 137
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
2238 0
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
979 17
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
1126 1
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
1101 1
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
850 0
|
存储 JavaScript 前端开发
如何高效实现 vue 文件批量下载及相关操作技巧
在Vue项目中,实现文件批量下载是常见需求。例如文档管理系统或图片库应用中,用户可能需要一次性下载多个文件。本文介绍了三种技术方案:1) 使用`file-saver`和`jszip`插件在前端打包文件为ZIP并下载;2) 借助后端接口完成文件压缩与传输;3) 使用`StreamSaver`解决大文件下载问题。同时,通过在线教育平台的实例详细说明了前后端的具体实现步骤,帮助开发者根据项目需求选择合适方案。
1321 0
|
JavaScript 前端开发 UED
Vue 项目中如何自定义实用的进度条组件
本文介绍了如何使用Vue.js创建一个灵活多样的自定义进度条组件。该组件可接受进度段数据数组作为输入,动态渲染进度段,支持动画效果和内容展示。当进度超出总长时,超出部分将以红色填充。文章详细描述了组件的设计目标、实现步骤(包括props定义、宽度计算、模板渲染、动画处理及超出部分的显示),并提供了使用示例。通过此组件,开发者可根据项目需求灵活展示进度情况,优化用户体验。资源地址:[https://pan.quark.cn/s/35324205c62b](https://pan.quark.cn/s/35324205c62b)。
773 0