如上例所示,vue 的核心思想是数据驱动,那数据怎么渲染到 DOM 中? new Vue 发生了什么 initState initData getData proxy 总结 执行 new Vue 的时候,执行 initMixin 先对 options 进行合并,初始化得到 this.$options 然后执行一系列的init方法,其中有initState,在initState中 把this.dat…

<div id="app">{{ message }}</div>;
var app = new Vue({
  el: '#app',
  mounted(){
    console.log(this.message)
    console.log(this._data.message)
  }
  data: {
    message: 'Hello Vue!'
  }
});

如上例所示,vue 的核心思想是数据驱动,那数据怎么渲染到 DOM 中?

new Vue 发生了什么

  • 构造函数Vue
// vue/src/core/instance/index.js
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');
  }
  // vue原型的一个方法
  this._init(options);
}
// 初始化定义的时候就定义了initMixin
initMixin(Vue);
  • initMixin
// vue/src/core/instance/init.js
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;
    // 把传入的option merge到$option上,通过$options.el就可以访问到vue对象的el
    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);
    initRender(vm);
    callHook(vm, 'beforeCreate');
    initInjections(vm); // resolve injections before data/props
    // 初始化State
    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);
    }
    // 判断el是否存在,在$mount方法建了DOM
    if (vm.$options.el) {
      vm.$mount(vm.$options.el);
    }
  };
}
  • initState
// vue/src/core/instance/state.js
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);
  // 在这里面initData
  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);
  }
}
  • initData
// vue/src/core/instance/state.js
function initData(vm: Component) {
  // 缓存data
  let data = vm.$options.data;
  // 先判断是否是个function,通常是一个function,而不是一个对象。function会retrun data
  // 把this.data赋给vm._data
  data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {};
  if (!isPlainObject(data)) {
    data = {};
    process.env.NODE_ENV !== 'production' && warn('data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm);
  }
  // proxy data on instance
  // 拿到对象的key
  const keys = Object.keys(data);
  // 拿到prop的props
  const props = vm.$options.props;
  // props和data不能相同,因为最终都会挂到vm实例上
  const methods = vm.$options.methods;
  let i = keys.length;
  while (i--) {
    const key = keys[i];
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(`Method "${key}" has already been defined as a data property.`, vm);
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(`The data property "${key}" is already declared as a prop. ` + `Use prop default value instead.`, vm);
    } else if (!isReserved(key)) {
      // 进行代理
      proxy(vm, `_data`, key);
    }
  }
  // 响应式data
  observe(data, true /* asRootData */);
}
  • getData
// vue/src/core/instance/state.js
export function getData(data: Function, vm: Component): any {
  // #7573 disable dep collection when invoking data getters
  // 把data return出来
  pushTarget();
  try {
    // 改变data指向
    return data.call(vm, vm);
  } catch (e) {
    handleError(e, vm, `data()`);
    return {};
  } finally {
    popTarget();
  }
}
  • proxy
// vue/src/core/instance/state.js
// 对值进行代理
export function proxy(target: Object, sourceKey: string, key: string) {
  // target就是vm,sourceKey就是`_data`
  // sourceKey就是_data
  // key就是message
  sharedPropertyDefinition.get = function proxyGetter() {
    // return this._data.message
    return this[sourceKey][key];
  };
  sharedPropertyDefinition.set = function proxySetter(val) {
    this[sourceKey][key] = val;
  };
  Object.defineProperty(target, key, sharedPropertyDefinition);
}

总结

执行 new Vue 的时候,执行 initMixin 先对 options 进行合并,初始化得到 this.$options 然后执行一系列的init方法,其中有initState,在initState中 把this.data赋给vm._data,执行proxy(vm, _data, key) proxy最终retrun出this._data.message。然后还有一系列的init,最终判断el是否存在,在$mount 去挂载 vm

暂无评论