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");
  }
  this._init(options);
}
//初始化_init方法  new的时候会用到此方法
initMixin(Vue);
//初始化  $get $set  $watch 方法
stateMixin(Vue);
//初始化 $on $once $off $emit 原型链上的方法
eventsMixin(Vue);
// 初始化  $forceUpdate  $destroy 原型链上的方法
//$destroy  会调用 beforeDestroy destroyed生命周期函数
//此方法只是混入原型链的方法  并不是初始化生命周期函数
lifecycleMixin(Vue);
// 初始化 $nextTick  还有 _render 方法
renderMixin(Vue);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

vue 初始化

路径 /Users/wangdapan/baidu/vue/vue/src/core/instance/init.js 这个方法是 new vue 的时候调用 比较重要 这个方法能看出来一些关于生命周期的不同 1:beforeCreate 这时候还未初始化什么东西 也就能获取到 vm 实例 还有$root 比如 props injections 注入的东西都还没获取到 2:created 这个能看到已经开始能获取到 injections、props、data, props 是在 initState 里可以获取到

initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, "beforeCreate");
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, "created");
1
2
3
4
5
6
7
8

双向绑定

_init->initState->initData->observe

从 Observer 里可以看到 每个$data 里都有一个__ob__就是从这里来的以及绑定的方式不同

数组是 this.observeArray
其他是 this.walk

重写数组的代码
import { def } from "../util/index";

const arrayProto = Array.prototype;
export const arrayMethods = Object.create(arrayProto);

const methodsToPatch = [
  "push",
  "pop",
  "shift",
  "unshift",
  "splice",
  "sort",
  "reverse",
];

/**
 * Intercept mutating methods and emit events
 */
methodsToPatch.forEach(function (method) {
  // cache original method
  const original = arrayProto[method];
  def(arrayMethods, method, function mutator(...args) {
    const result = original.apply(this, args);
    const ob = this.__ob__;
    let inserted;
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
        break;
    }
    if (inserted) ob.observeArray(inserted);
    // notify change
    ob.dep.notify();
    return result;
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

vue hook

vue 官方支持 this.$on("hook:created",funciton) 这样的使用方式,但是要注意定时的时间顺序,要确保在调用之前的生命周期函数里调用.

如果存在 hook vue 官方会把_hasHookEvent 设置为 true

vm._hasHookEvent = true;
1
上次更新: 2021/10/28 02:35:22
贡献者: wangdapan