Vue2 源码漫游(一)

2,875 阅读8分钟

Vue2 源码漫游(一)

描述:

Vue框架中的基本原理可能大家都基本了解了,但是还没有漫游一下源码。
所以,觉得还是有必要跑一下。
由于是代码漫游,所以大部分为关键性代码,以主线路和主要分支的代码为主,大部分理解都写在代码注释中。

一、代码主线

文件结构1-->4,代码执行顺序4-->1

1.platforms/web/entry-runtime.js/index.js

web不同平台入口;

/* @flow */

import Vue from './runtime/index'

export default Vue

2.runtime/index.js

为Vue配置一些属性方法

/* @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'

// install platform specific utils
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
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 */
Vue.nextTick(() => {
  if (config.devtools) {
    if (devtools) {
      devtools.emit('init', Vue)
    } else if (process.env.NODE_ENV !== 'production' && 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' &&
    config.productionTip !== false &&
    inBrowser && 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

3.core/index.js

/* @flow */

import config from '../config'
import { initUse } from './use'
import { initMixin } from './mixin'
import { initExtend } from './extend'
import { initAssetRegisters } from './assets'
import { set, del } from '../observer/index'
import { ASSET_TYPES } from 'shared/constants'
import builtInComponents from '../components/index'

import {
  warn,
  extend,
  nextTick,
  mergeOptions,
  defineReactive
} from '../util/index'

export function initGlobalAPI (Vue: GlobalAPI) {
  // 重写config,创建了一个configDef对象,最终目的是为了Object.defineProperty(Vue, 'config', configDef)
  const configDef = {}
  configDef.get = () => config
  if (process.env.NODE_ENV !== 'production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  Object.defineProperty(Vue, 'config', configDef)
  // 具体Vue.congfig的具体内容就要看../config文件了

  // exposed util methods.
  // NOTE: these are not considered part of the public API - avoid relying on them unless you are aware of the risk.
  // 添加一些方法,但是该方法并不是公共API的一部分。源码中引入了flow.js
  Vue.util = {
    warn, // 查看'../util/debug'
    extend,//查看'../sharde/util'
    mergeOptions,//查看'../util/options'
    defineReactive//查看'../observe/index'
  }

  Vue.set = set //查看'../observe/index' 
  Vue.delete = del//查看'../observe/index'
  Vue.nextTick = nextTick//查看'../util/next-click'.在callbacks中注册回调函数

  // 创建一个纯净的options对象,添加components、directives、filters属性
  Vue.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 = Vue

  // ../components/keep-alive.js  拷贝组件对象。该部分最重要的一部分。
  extend(Vue.options.components, builtInComponents)
  // Vue.options = {
  //   components : {
  //     KeepAlive : {
  //       name : 'keep-alive',
  //       abstract : true,
  //       created : function created(){},
  //       destoryed : function destoryed(){},
  //       props : {
  //         exclude : [String, RegExp, Array],
  //         includen : [String, RegExp, Array],
  //         max : [String, Number]
  //       },
  //       render : function render(){},
  //       watch : {
  //         exclude : function exclude(){},
  //         includen : function includen(){},
  //       }
  //     },
  //     directives : {},
  //     filters : {},
  //     _base : Vue
  //   }
  // }
  // 添加Vue.use方法,使用插件,内部维护一个插件列表_installedPlugins,如果插件有install方法就执行自己的install方法,否则如果plugin是一个function就执行这个方法,传参(this, args)
  initUse(Vue)
  // ./mixin.js 添加Vue.mixin方法,this.options = mergeOptions(this.options, mixin),
  initMixin(Vue)
  // ./extend.js 添加Vue.cid(每一个够着函数实例都有一个cid,方便缓存),Vue.extend(options)方法
  initExtend(Vue)
  // ./assets.js 创建收集方法Vue[type] = function (id: string, definition: Function | Object),其中type : component / directive / filter
  initAssetRegisters(Vue)
}

Vue.util对象的部分解释:

  • Vue.util.warn
     warn(msg, vm) 警告方法代码在util/debug.js,
     通过var trac = generateComponentTrace(vm)方法vm=vm.$parent递归收集到msg出处。
     然后判断是否存在console对象,如果有 console.error(`[Vue warn]: ${msg}${trace}`)。
     如果config.warnHandle存在config.warnHandler.call(null, msg, vm, trace)
    • Vue.util.extend
      extend (to: Object, _from: ?Object):Object Object类型浅拷贝方法代码在shared/util.js
    • Vue.util.mergeOptions
      合并,vue实例化和实现继承的核心方法,代码在shared/options.js
      mergeOptions (
       parent: Object,
       child: Object,
       vm?: Component
      )
      先通过normalizeProps、normalizeInject、normalizeDirectives以Object-base标准化,然后依据strats合并策略进行合并。
      strats是对data、props、watch、methods等实例化参数的合并策略。除此之外还有defaultStrat默认策略。
      后期暴露的mixin和Vue.extend()就是从这里出来的。[官网解释][1]
    • Vue.util.defineReactive
      大家都知道的数据劫持核心方法,代码在shared/util.js
      defineReactive (
       obj: Object,
       key: string,
       val: any,
       customSetter?: ?Function,
       shallow?: boolean
      )

4.instance/index.js 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) {
  // 判断是否是new调用。
  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._init(options)内部方法,./init.js
initMixin(Vue)
/**
 * ./state.js
 * 添加属性和方法
 * Vue.prototype.$data 
 * Vue.prototype.$props
 * Vue.prototype.$watch
 * Vue.prototype.$set
 * Vue.prototype.$delete
 */ 
stateMixin(Vue)
/**
 * ./event.js
 * 添加实例事件
 * Vue.prototype.$on
 * Vue.prototype.$once
 * Vue.prototype.$off
 * Vue.prototype.$emit
 */ 
eventsMixin(Vue)
/**
 * ./lifecycle.js
 * 添加实例生命周期方法
 * Vue.prototype._update
 * Vue.prototype.$forceUpdate
 * Vue.prototype.$destroy
 */ 
lifecycleMixin(Vue)
/**
 * ./render.js
 * 添加实例渲染方法
 * 通过执行installRenderHelpers(Vue.prototype);为实例添加很多helper
 * Vue.prototype.$nextTick
 * Vue.prototype._render
 */ 
renderMixin(Vue)

export default Vue

5.instance/init.js

初始化,完成主组件的所有动作的主线。从这儿出发可以理清observer、watcher、compiler 、render等

import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'

let uid = 0

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = 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
    // 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 {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    /**
    * 添加vm.$createElement vm.$vnode vm.$slots vm.
    * 创建vm.$attrs  /  vm.$listeners 并且转换为getter和setter
    * 
    */
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props vm.$scopedSlots 
    /**
    * 1、创建 vm._watchers = [];
    * 2、执行if (opts.props) { initProps(vm, opts.props); } 验证props后调用defineReactive转化,并且代理数据proxy(vm, "_props", key);
    * 3、执行if (opts.methods) { initMethods(vm, opts.methods); } 然后vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
    * 4、处理data,
    * if (opts.data) {
    *    initData(vm);
    * } else {
    *    observe(vm._data = {}, true /* asRootData */);
    * }
    * 5、执行initData:
    *       (1)先判断data的属性是否有与methods和props值同名
    *       (2)获取vm.data(如果为function,执行getData(data, vm)),代理proxy(vm, "_data", key);
    *       (3)执行 observe(data, true /* asRootData */);递归观察
    * 6、完成observe,具体看解释
    */
    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)
    }

    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

二、observe 响应式数据转换

1.前置方法 observe(value, asRootData)

function observe (value, asRootData) {
  // 如果value不是是Object 或者是VNode这不用转换
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  var ob;
  // 如果已经转换就复用
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__;
  } else if (
    //一堆必要的条件判断
    observerState.shouldConvert &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    //这才是observe主体
    ob = new Observer(value);
  }
  if (asRootData && ob) {
    ob.vmCount++;
  }
  return ob
}

2.Observer 类

var Observer = function Observer (value) {
  // 当asRootData = true时,其实可以将value当做vm.$options.data,后面都这样方便理解
  this.value = value;
  /**
  * 为vm.data创建一个dep实例,可以理解为一个专属事件列表维护对象
  * 例如: this.dep = { id : 156, subs : [] }
  * 实例方法: this.dep.__proto__ = { addSub, removeSub, depend, notify, constructor }
  */
  this.dep = new Dep();
  //记录关联的vm实例的数量
  this.vmCount = 0;
  //为vm.data 添加__ob__属性,值为当前observe实例,并且转化为响应式数据。所以看一个value是否为响应式就可以看他有没有__ob__属性
  def(value, '__ob__', this);
  //响应式数据转换分为数组、对象两种。
  if (Array.isArray(value)) {
    var augment = hasProto
      ? protoAugment
      : copyAugment;
    augment(value, arrayMethods, arrayKeys);
    this.observeArray(value);
  } else {
    //对象的转换,而且walk是Observer的实例方法,请记住
    this.walk(value);
  }
};

3.walk

该方法要将vm.data的所有属性都转化为getter/setter模式,所以vm.data只能是Object。数组的转换不一样,这里暂不做讲解。

Observer.prototype.walk = function walk (obj) {
  // 得到key的列表
  var keys = Object.keys(obj);
  for (var i = 0; i < keys.length; i++) {
    //核心方法:定义响应式数据的方法  defineReactive(对象, 属性, 值);这样看是不是就很爽了
    defineReactive(obj, keys[i], obj[keys[i]]);
  }
};

4.defineReactive(obj, key, value)

function defineReactive (
  obj,
  key,
  val,
  customSetter, //自定义setter,为了测试
  shallow //是否只转换这一个属性后代不管控制参数,false :是,true : 否
) {
  /**
  * 又是一个dep实例,其实作用与observe中的dep功能一样,不同点:
  *     1.observe实例的dep对象是父级vm.data的订阅者维护对象
  *     2.这个dep是vm.data的属性key的订阅者维护对象,因为val有可能也是对象
  *     3.这里的dep没有写this.dep是因为defineReactive是一个方法,不是构造函数,所以使用闭包锁在内存中
  */
  var dep = new Dep();
  // 获取key的属性描述符
  var property = Object.getOwnPropertyDescriptor(obj, key);
  // 如果key属性不可设置,则退出该函数
  if (property && property.configurable === false) {
    return
  }

  // 为了配合那些已经的定义了getter/setter的情况
  var getter = property && property.get;
  var setter = property && property.set;

  //递归,因为没有传asRootData为true,所以vm.data的vmCount是部分计数的。因为它还是属于vm的数据
  var childOb = !shallow && observe(val);
  /**
  * 全部完成后observe也就完成了。但是,每个属性的dep都没启作用。
  * 这就是所谓的依赖收集了,后面继续。
  */
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      var value = getter ? getter.call(obj) : val;
      if (Dep.target) {
        dep.depend();
        if (childOb) {
          childOb.dep.depend();
          if (Array.isArray(value)) {
            dependArray(value);
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      var value = getter ? getter.call(obj) : val;
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter();
      }
      if (setter) {
        setter.call(obj, newVal);
      } else {
        val = newVal;
      }
      childOb = !shallow && observe(newVal);
      dep.notify();
    }
  });
}

三、依赖收集

一些个人理解:
    1、Watcher 订阅者
        可以将它理解为,要做什么。具体的体现就是Watcher的第二个参数expOrFn。
    2、Observer 观察者
        其实观察的体现就是getter/setter能够观察数据的变化(数组的实现不同)。
    3、dependency collection 依赖收集
        订阅者(Watcher)是干事情的,是一些指令、方法、表达式的执行形式。它运行的过程中肯定离不开数据,所以就成了这些数据的依赖项目。因为离不开^_^数据。
        数据是肯定会变的,那么数据变了就得通知数据的依赖项目(Watcher)让他们再执行一下。
        依赖同一个数据的依赖项目(Watcher)可能会很多,为了保证能够都通知到,所以需要收集一下。
    4、Dep 依赖收集器构造函数
        因为数据是由深度的,在不同的深度有不同的依赖,所以我们需要一个容器来装起来。
        Dep.target的作用是保证数据在收集依赖项(Watcher)时,watcher是对这个数据依赖的,然后一个个去收集的。

1、Watcher

Watcher (vm, expOrFn, cb, options)
参数:
{string | Function} expOrFn
{Function | Object} callback
{Object} [options]
    {boolean} deep
    {boolean} user
    {boolean} lazy
    {boolean} sync
在Vue的整个生命周期当中,会有4类地方会实例化Watcher:
    Vue实例化的过程中有watch选项
    Vue实例化的过程中有computed计算属性选项
    Vue原型上有挂载$watch方法: Vue.prototype.$watch,可以直接通过实例调用this.$watch方法
    Vue生成了render函数,更新视图时

    Watcher接收的参数当中expOrFn定义了用以获取watcher的getter函数。expOrFn可以有2种类型:string或function.若为string类型,
首先会通过parsePath方法去对string进行分割(仅支持.号形式的对象访问)。在除了computed选项外,其他几种实例化watcher的方式都
是在实例化过程中完成求值及依赖的收集工作:this.value = this.lazy ? undefined : this.get().在Watcher的get方法中:
var Watcher = function Watcher (
  vm,
  expOrFn,
  cb,
  options
) {
  this.vm = vm;
  vm._watchers.push(this);
  // options
  if (options) {
    this.deep = !!options.deep;
    this.user = !!options.user;
    this.lazy = !!options.lazy;
    this.sync = !!options.sync;
  } else {
    this.deep = this.user = this.lazy = this.sync = false;
  }
  //相关属性
  this.cb = cb;
  this.id = ++uid$2; // uid for batching
  this.active = true;
  this.dirty = this.lazy; // for lazy watchers
  //
  this.deps = [];
  this.newDeps = [];
  //set类型的ids
  this.depIds = new _Set();
  this.newDepIds = new _Set();
  // 表达式
  this.expression = process.env.NODE_ENV !== 'production'
    ? expOrFn.toString()
    : '';
  // 创建一个getter
  if (typeof expOrFn === 'function') {
    this.getter = expOrFn;
  } else {
    this.getter = parsePath(expOrFn);
    if (!this.getter) {
      this.getter = function () {};
      process.env.NODE_ENV !== 'production' && warn(
        "Failed watching path: \"" + expOrFn + "\" " +
        'Watcher only accepts simple dot-delimited paths. ' +
        'For full control, use a function instead.',
        vm
      );
    }
  }
  this.value = this.lazy
    ? undefined
    : this.get();//执行get收集依赖项
};

2、Watcher.prototype.get

通过设置观察值(this.value)调用this.get方法,执行this.getter.call(vm, vm),这个过程中只要获取了某个响应式数据。那么肯定会触发该数据的getter方法。因为当前的Dep.target = watcher。所以就将该watcher作为了这个响应数据的依赖项。因为watcher在执行过程中的确需要、使用了它、所以依赖它。

Watcher.prototype.get = function get () {
  //将这个watcher观察者实例添加到Dep.target,表明当前为this.expressoin的依赖收集时间
  pushTarget(this);
  var value;
  var vm = this.vm;
  try {
    /**
    * 执行this.getter.call(vm, vm):
    *     1、如果是function则相当于vm.expOrFn(vm),只要在这个方法执行的过程中有从vm上获取属性值的都会触发该属性值的get方法从而完成依赖收集。因为现在Dep.target=this. 
    *     2、如果是字符串(如a.b),那么this.getter.call(vm, vm)就相当于vm.a.b
    */ 
    value = this.getter.call(vm, vm);
  } catch (e) {
    if (this.user) {
      handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
    } else {
      throw e
    }
  } finally {
    // "touch" every property so they are all tracked as
    // dependencies for deep watching
    if (this.deep) {
      traverse(value);
    }
    popTarget();
    this.cleanupDeps();
  }
  return value
};

3、getter/setter

Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      var value = getter ? getter.call(obj) : val;
      if (Dep.target) {
        //依赖收集,这里又饶了一圈,看后面的解释
        dep.depend();
        if (childOb) {
          childOb.dep.depend();
          if (Array.isArray(value)) {
            dependArray(value);
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      var value = getter ? getter.call(obj) : val;
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter();
      }
      if (setter) {
        setter.call(obj, newVal);
      } else {
        val = newVal;
      }
      childOb = !shallow && observe(newVal);
      //数据变动出发所有依赖项
      dep.notify();
    }
  });

- 依赖收集具体动作:

//调用的自己dep的实例方法
Dep.prototype.depend = function depend () {
  if (Dep.target) {
    //调用的是当前Watcher实例的addDe方法,并且把dep对象传过去了
    Dep.target.addDep(this);
  }
};

Watcher.prototype.addDep = function addDep (dep) {
  var id = dep.id;
  if (!this.newDepIds.has(id)) {
    //为这个watcher统计内部依赖了多少个数据,以及其他公用该数据的watcher
    this.newDepIds.add(id);
    this.newDeps.push(dep);
    if (!this.depIds.has(id)) {
      //继续为数据收集依赖项目的步骤
      dep.addSub(this);
    }
  }
};
Dep.prototype.addSub = function addSub (sub) {
  this.subs.push(sub);
};

- 数据变动出发依赖动作:

Dep.prototype.notify = function notify () {
  // stabilize the subscriber list first
  var subs = this.subs.slice();
  for (var i = 0, l = subs.length; i < l; i++) {
    subs[i].update();
  }
};
//对当前watcher的处理
Watcher.prototype.update = function update () {
  /* istanbul ignore else */
  if (this.lazy) {
    this.dirty = true;
  } else if (this.sync) {
    this.run();
  } else {
    queueWatcher(this);
  }
};
//把一个观察者推入观察者队列。
//具有重复id的作业将被跳过,除非它是
//当队列被刷新时被推。
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true
      nextTick(flushSchedulerQueue)
    }
  }
}