实例讲解vue源码架构

下载

去github上下载Vue https://github.com/vuejs/vue

npm install
npm run dev

运行起来

rollup + flow

vue使用使用rollup打包,flow规范数据类型

rollup可以先用webpack套用,读起来差不多,时间有限,毕竟只有5分钟,这个就不用去看rollup文档了

入口

打开package.json

我们看scripts配置

"dev": "rollup -w -c scripts/config.js --environment TARGET:web-full-dev",
 "dev:cjs": "rollup -w -c scripts/config.js --environment TARGET:web-runtime-cjs-dev",

找到scripts/config.js

打开

根据配置TARGET的不同会选择不同的config

同时在这里配置了process.env.NODE_ENV 环境

TARGET有CommonJS,ES Modules,UMD关于js引入类型的

还有weex,ssr

'web-runtime-cjs-dev': {
  entry: resolve('web/entry-runtime.js'),
  dest: resolve('dist/vue.runtime.common.dev.js'),
  format: 'cjs',
  env: 'development',
  banner
 }

在alias.js下设置了别名路径

我们先介绍src/platforms

里面有web和weex 分别的web和weex入口

在web文件下是CommonJS,ES Modules,UMD关于js引入类型,server的打包入口

打开web/entry-runtime.js

引入

import Vue from './runtime/index'
export default Vue

打开./runtime/index

import Vue from 'core/index'

Vue.prototype.$mount = function (
 el?: string | Element,
 hydrating?: boolean
): Component {
 el = el && inBrowser ? query(el) : undefined
 return mountComponent(this, el, hydrating)
}
export default Vue

在vue原型上添加了mount方法

处理了devtools,没有安装提醒安装devtools

给了这句提示dev环境提示

You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

platforms目录夹讲解完毕

core目录

打开core/instance/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

先执行的是initMixin(Vue)

打开init

export function initMixin (Vue) {
 Vue.prototype._init = function (options?: Object) {
  const vm = this
  // a uid
  vm._uid = uid++

  let startTag, endTag
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   startTag = `vue-perf-start:${vm._uid}`
   endTag = `vue-perf-end:${vm._uid}`
   mark(startTag)
  }

  // a flag to avoid this being observed
  vm._isVue = true
  // 处理传入的options
  // merge options
  if (options && options._isComponent) {
   // optimize internal component instantiation
   // since dynamic options merging is pretty slow, and none of the
   // internal component options needs special treatment.
   initInternalComponent(vm, options)
  } else {
    // 传入的options,默认的options一起合并挂载到vm.$options上
   vm.$options = mergeOptions(
    resolveConstructorOptions(vm.constructor),
    options || {},
    vm
   )
  }
  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
   // 代理
   initProxy(vm)
  } else {
   vm._renderProxy = vm
  }
  // 生命周期
  initLifecycle(vm)
   // emit on 事件
  initEvents(vm)
  // 处理render vdom
  initRender(vm)
  callHook(vm, 'beforeCreate')
  // 处理Injections
  initInjections(vm) // resolve injections before data/props
  // 双向数据绑定,监听订阅
  initState(vm)
  initProvide(vm) // resolve provide after data/props
  callHook(vm, 'created')

  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   vm._name = formatComponentName(vm, false)
   mark(endTag)
   measure(`vue ${vm._name} init`, startTag, endTag)
  }
  // 渲染到dom
  if (vm.$options.el) {
   vm.$mount(vm.$options.el)
  }
 }
}

lifecycle

打开 lifecycle

export function callHook (vm: Component, hook: string) {
 // disable dep collection when invoking lifecycle hooks
 pushTarget()
 //执行对象的周期函数,周期函数最后被处理成数组
 const handlers = vm.$options[hook]
 const info = `${hook} hook`
 if (handlers) {
  for (let i = 0, j = handlers.length; i < j; i++) {
   invokeWithErrorHandling(handlers[i], vm, null, vm, info)
  }
 }
 if (vm._hasHookEvent) {
  vm.$emit('hook:' + hook)
 }
 popTarget()

callHook 的时候,是执行相应周期,开发者在周期函数里所写的

Events

initEvents实现了 emit on 等方法,请参考监听者订阅者模式,这里不详解

render
renderMixin函数
添加了 $nextTick _render 原型对象

$nextTick会在dom跟新后立即调用

nextTick(fn, this)是一个自执行函数

_render返回的是node的js数据,还不是dom

做了Vdom

initRender函数
给vm添加了_c和 $createElement用来渲染的方法

state

if (!(key in vm)) {
   proxy(vm, `_props`, key)
  }

给vue属性做代理,访问this.a可以得到this.data.a 的值

export function initState (vm: Component) {
 vm._watchers = []
 const opts = vm.$options
 if (opts.props) initProps(vm, opts.props)
 if (opts.methods) initMethods(vm, opts.methods)
 if (opts.data) {
  initData(vm)
 } else {
  observe(vm._data = {}, true /* asRootData */)
 }
 if (opts.computed) initComputed(vm, opts.computed)
 if (opts.watch && opts.watch !== nativeWatch) {
  initWatch(vm, opts.watch)
 }
}

给数据做监听

stateMixin函数

添加原型对象

Vue.prototype.$set = set
Vue.prototype.$delete = del

其他

src/compiler 做了编译处理

core/componetd 做了keep-alive

core/util 封装了通用方法

core/vdom vdom算法

以上整体架构分析完毕

(0)

相关推荐

  • vue中轮训器的使用

    核心代码: <template> <div > {{log}} </div> </template> <script> export default { name: "TrainingInRotation", data(){ return { log:0, timerId:1, // 模拟计时器id,唯一性 timerObj :{}, // 计时器存储器 } }, created(){ this.startTraining()

  • vue+webpack中配置ESLint

    一.ESLint 协同开发过程中,经常感受到来自代码检视的恶意.代码习惯不一致,看半天:居然提交低级错误,我的天(╯‵□′)╯︵┻━┻!...研究了一番,决定使用ESLint来做代码规范检查. 二.配置方式 JavaScript注释:通过JavaScript注释把配置信息嵌入代码中. package.json:在package.json文件中的eslintConfig字段中指定配置. 配置文件:通过.eslintrc.(js/json/yaml/yml)的独立文件来为整个目录或者子目录指定配置信

  • 详解如何在vue项目中使用eslint+prettier格式化代码

    对于前端代码风格这个问题一直是经久不衰,每个人都有自己的代码风格,每次看到别人代码一团糟时候我们都会吐槽下.今天给大家介绍如何使用eslint+prettier统一代码风格. 对于eslint大家应该比较了解了,是用来校验代码规范的.给大家介绍下prettier,prettier是用来统一代码风格,格式化代码的,支持js.ts.css.less.scss.json.jsx.并且集成了vscode.vim.webstorm.sublime text插件. 如果你的项目中采用的是ellint默认规则

  • 详解ESLint在Vue中的使用小结

    ESLint是一个QA工具,用来避免低级错误和统一代码的风格 ESLint的用途 1.审查代码是否符合编码规范和统一的代码风格: 2.审查代码是否存在语法错误: 中文网地址 http://eslint.cn/ 使用VSCode编译器在Vue项目中的使用 在初始化项目时选择是否使用 ESLint管理代码(选择Y则默认开启) Use ESLint to lint your code? (Y/n) 默认使用的是此标准https://github.com/standard/standard/blob/m

  • vue中eslintrc.js配置最详细介绍

    本文是对vue项目中自带文件eslintrc.js的内容解析, 介绍了各个eslint配置项的作用,以及为什么这样设置. 比较详细,看完能对eslint有较为全面的了解,基本解除对该文件的疑惑. /** * 参考文档 * [eslint英文文档]https://eslint.org/docs/user-guide/configuring * [eslint中文文档]http://eslint.cn/docs/rules/ */ /** * eslint有三种使用方式 * [1]js代码中通过注释

  • 在vue项目中使用Jquery-contextmenu插件的步骤讲解

    使用步骤: 1.安装: npm i jquery-contextmenu --save-dev 2.在main.js文件中引包 import Jquery_contextmenu from 'jquery-contextmenu' Vue.use(Jquery_contextmenu) import 'jquery-contextmenu/dist/jquery.contextMenu.css' 注意: 在引入样式时可以点击进去jquery-contextmenu的安装目录中查找对应的css文件

  • 在Vue项目中取消ESLint代码检测的步骤讲解

    在Vue项目中编写代码的时候经常会碰到这种烦人的无故报错,其实这是ESLint代码,如图下: 解决办法: File>Settings>ESLint>取消检测即可(将Enable选项去勾选)>apply,如下图: 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持.如果你想了解更多相关内容请查看下面相关链接

  • 在Vue项目中引入JQuery-ui插件的讲解

    安装:  npm install jquery-ui-dist -S 引入: import 'jquery-ui-dist/jquery-ui' 更改配置文件: 1.添加jquery:'jquery' resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), jquery:'jquery', } }, // 添加代码 plugins:

  • vue中子组件传递数据给父组件的讲解

    发送者: modifyName:是接受者的键,也就是发送和接收的唯一标识 itemObj:是一个对象 this.$emit("modifyName",this.itemObj); 接受者: <common-table 是一个自定义组件 @modifyName 就是发送时所定义的唯一标识 modifyName 是一个函数 <common-table @modifyName="modifyName"></common-table> 总结 以

  • vscode下vue项目中eslint的使用方法

    前言 在vscode的vue项目中,关于代码检查和格式化,遇到各种各样的问题,比如: 不清楚安装的拓展的功能,导致安装了重复功能的拓展 右键格式化文档的时候,不是按eslint的规则来格式化,导致需要我再次手动调整 保存时不能自动修复代码 以下通过自己的实践,进行了相应配置,目前可以实现: 仅安装2个推荐的拓展 右键格式化文档按照eslint规则,不会产生错误 保存时自动修复代码 vscode 拓展安装 eslint 拓展 该拓展本身不带任何插件,当前项目要使用该拓展,需要安装相应的npm包(全

随机推荐