Vue源码:指令和生命周期

新建Vue实例后,会将参数与数据绑定在Vue上,并通过observe方法将数据变为响应式的,并通过Watcher进行监听,通过Compile方法进行编译。指令在compileElement方法中进行判断执行。

v-model做的事:

  • 添加Watcher,只要v-model(a),就需要向a身上添加Watcher
  • 得到值并显示
  • 添加input的监听事件,改变值

index.js

import Vue from './Vue.js';

window.Vue = Vue;

Vue.js

import Compile from "./Compile.js";
import observe from './observe.js';
import Watcher from './Watcher.js';

export default class Vue {
    constructor(options) {
        // 把参数options对象存为$options
        this.$options = options || {};
        // 数据
        this._data = options.data || undefined;
        observe(this._data);
        // 默认数据要变为响应式的,这里就是生命周期
        this._initData();
        // 调用默认的watch
        this._initWatch();
        // 模板编译
        new Compile(options.el, this);
    }

    _initData() {
        let self = this;
        Object.keys(this._data).forEach(key => {
            Object.defineProperty(self, key, {
                get: () => {
                    return self._data[key];
                },
                set: (newVal) => {
                    self._data[key] = newVal;
                }
            });
        });
    }

    _initWatch() {
        let self = this;
        let watch = this.$options.watch;
        Object.keys(watch).forEach(key => {
            new Watcher(self, key, watch[key]);
        });
    }
};

Compile.js

import Watcher from './Watcher.js';

export default class Compile {
  constructor(el, vue) {
    // vue实例
    this.$vue = vue;
    // 挂载点
    this.$el = document.querySelector(el);
    // 如果用户传入了挂载点
    if (this.$el) {
      // 调用函数,让节点变为fragment,类似于mustache中的tokens。实际上用的是AST,这里就是轻量级的,fragment
      let $fragment = this.node2Fragment(this.$el);
      // 编译
      this.compile($fragment);
      // 替换好的内容要上树
      this.$el.appendChild($fragment);
    }
  }

  // 将el选择器所有内容生成虚拟节点
  node2Fragment(el) {
    let fragment = document.createDocumentFragment();

    let child;
    // 让所有DOM节点,都进入fragment
    while (child = el.firstChild) {
      fragment.appendChild(child);
    }
    return fragment;
  }

  // 编译
  compile(el) {
    // console.log(el);
    // 得到子元素
    let childNodes = el.childNodes;
    let self = this;

    let reg = /\{\{(.*)\}\}/;

    childNodes.forEach(node => {
      let text = node.textContent;
      (text);
      // console.log(node.nodeType);
      // console.log(reg.test(text));
      if (node.nodeType == 1) {
        self.compileElement(node);
      } else if (node.nodeType == 3 && reg.test(text)) {
        let name = text.match(reg)[1];
        self.compileText(node, name);
      }
    });
  }

  compileElement(node) {
    // console.log(node);
    // 这里的方便之处在于不是将HTML结构看做字符串,而是真正的属性列表
    let nodeAttrs = node.attributes;
    let self = this;

    // 类数组对象变为数组
    [].slice.call(nodeAttrs).forEach(attr => {
      // 这里就分析指令
      let attrName = attr.name;
      let value = attr.value;
      // 指令都是v-开头的
      let dir = attrName.substring(2);

      // 看看是不是指令
      if (attrName.indexOf('v-') == 0) {
        // v-开头的就是指令
        if (dir == 'model') {
          // console.log('发现了model指令', value);
          new Watcher(self.$vue, value, value => {
            node.value = value;
          });
          let v = self.getVueVal(self.$vue, value);
          node.value = v;

          // 添加监听
          node.addEventListener('input', e => {
            let newVal = e.target.value;
            self.setVueVal(self.$vue, value, newVal);
            v = newVal;
          });
        } else if (dir == 'if') {
          // console.log('发现了if指令', value);
        }
      }
    });
  }

  compileText(node, name) {
    // console.log('AA', name);
    // console.log('BB', this.getVueVal(this.$vue, name));
    node.textContent = this.getVueVal(this.$vue, name);
    new Watcher(this.$vue, name, value => {
      node.textContent = value;
    });
  }

  getVueVal(vue, exp) {
    let val = vue;
    exp = exp.split('.');
    exp.forEach(k => {
      val = val[k];
    });

    return val;
  }

  setVueVal(vue, exp, value) {
    let val = vue;
    exp = exp.split('.');
    exp.forEach((k, i) => {
      if (i < exp.length - 1) {
        val = val[k];
      } else {
        val[k] = value;
      }
    });

  }
}

array.js

import { def } from './utils.js';

// 得到Array.prototype
const arrayPrototype = Array.prototype;

// 以Array.prototype为原型创建arrayMethods对象,并暴露
export const arrayMethods = Object.create(arrayPrototype);

// 要被改写的7个数组方法
const methodsNeedChange = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
];

methodsNeedChange.forEach(methodName => {
    // 备份原来的方法,因为push、pop等7个函数的功能不能被剥夺
    const original = arrayPrototype[methodName];
    // 定义新的方法
    def(arrayMethods, methodName, function () {
        // 恢复原来的功能
        const result = original.apply(this, arguments);
        // 把类数组对象变为数组
        const args = [...arguments];
        // 把这个数组身上的__ob__取出来,__ob__已经被添加了,为什么已经被添加了?因为数组肯定不是最高层,比如obj.g属性是数组,obj不能是数组,第一次遍历obj这个对象的第一层的时候,已经给g属性(就是这个数组)添加了__ob__属性。
        const ob = this.__ob__;

        // 有三种方法push\unshift\splice能够插入新项,现在要把插入的新项也要变为observe的
        let inserted = [];

        switch (methodName) {
            case 'push':
            case 'unshift':
                inserted = args;
                break;
            case 'splice':
                // splice格式是splice(下标, 数量, 插入的新项)
                inserted = args.slice(2);
                break;
        }

        // 判断有没有要插入的新项,让新项也变为响应的
        if (inserted) {
            ob.observeArray(inserted);
        }

        // console.log('啦啦啦');

        ob.dep.notify();

        return result;
    }, false);
});

defineReactive.js

import observe from './observe.js';
import Dep from './Dep.js';

export default function defineReactive(data, key, val) {
    const dep = new Dep();
    // console.log('我是defineReactive', key);
    if (arguments.length == 2) {
        val = data[key];
    }

    // 子元素要进行observe,至此形成了递归。这个递归不是函数自己调用自己,而是多个函数、类循环调用
    let childOb = observe(val);

    Object.defineProperty(data, key, {
        // 可枚举
        enumerable: true,
        // 可以被配置,比如可以被delete
        configurable: true,
        // getter
        get() {
            // console.log('你试图访问' + key + '属性');
            // 如果现在处于依赖收集阶段
            if (Dep.target) {
                dep.depend();
                if (childOb) {
                    childOb.dep.depend();
                }
            }
            return val;
        },
        // setter
        set(newValue) {
            console.log('你试图改变' + key + '属性', newValue);
            if (val === newValue) {
                return;
            }
            val = newValue;
            // 当设置了新值,这个新值也要被observe
            childOb = observe(newValue);
            // 发布订阅模式,通知dep
            dep.notify();
        }
    });
};

Dep.js

let uid = 0;
export default class Dep {
    constructor() {
        // console.log('我是DEP类的构造器');
        this.id = uid++;

        // 用数组存储自己的订阅者。subs是英语subscribes订阅者的意思。
        // 这个数组里面放的是Watcher的实例
        this.subs = [];
    }
    // 添加订阅
    addSub(sub) {
        this.subs.push(sub);
    }
    // 添加依赖
    depend() {
        // Dep.target就是一个我们自己指定的全局的位置,你用window.target也行,只要是全剧唯一,没有歧义就行
        if (Dep.target) {
            this.addSub(Dep.target);
        }
    }
    // 通知更新
    notify() {
        // console.log('我是notify');
        // 浅克隆一份
        const subs = this.subs.slice();
        // 遍历
        for (let i = 0, l = subs.length; i < l; i++) {
            subs[i].update();
        }
    }
};

observe.js

import Observer from './Observer.js';
export default function (value) {
    // 如果value不是对象,什么都不做
    if (typeof value != 'object') return;
    // 定义ob
    let ob;
    if (typeof value.__ob__ !== 'undefined') {
        ob = value.__ob__;
    } else {
        ob = new Observer(value);
    }
    return ob;
}

Observer.js

import { def } from './utils.js';
import defineReactive from './defineReactive.js';
import { arrayMethods } from './array.js';
import observe from './observe.js';
import Dep from './Dep.js';

export default class Observer {
    constructor(value) {
        // 每一个Observer的实例身上,都有一个dep
        this.dep = new Dep();
        // 给实例(this,一定要注意,构造函数中的this不是表示类本身,而是表示实例)添加了__ob__属性,值是这次new的实例
        def(value, '__ob__', this, false);
        // console.log('我是Observer构造器', value);
        // 不要忘记初心,Observer类的目的是:将一个正常的object转换为每个层级的属性都是响应式(可以被侦测的)的object
        // 检查它是数组还是对象
        if (Array.isArray(value)) {
            // 如果是数组,要非常强行的蛮干:将这个数组的原型,指向arrayMethods
            Object.setPrototypeOf(value, arrayMethods);
            // 让这个数组变的observe
            this.observeArray(value);
        } else {
            this.walk(value);
        }
    }
    // 遍历
    walk(value) {
        for (let k in value) {
            defineReactive(value, k);
        }
    }
    // 数组的特殊遍历
    observeArray(arr) {
        for (let i = 0, l = arr.length; i < l; i++) {
            // 逐项进行observe
            observe(arr[i]);
        }
    }
};

util.js

export const def = function (obj, key, value, enumerable) {
    Object.defineProperty(obj, key, {
        value,
        enumerable,
        writable: true,
        configurable: true
    });
};

Watcher.js

import Dep from "./Dep";

let uid = 0;
export default class Watcher {
    constructor(target, expression, callback) {
        console.log('我是Watcher类的构造器');
        this.id = uid++;
        this.target = target;
        this.getter = parsePath(expression);
        this.callback = callback;
        this.value = this.get();
    }
    update() {
        this.run();
    }
    get() {
        // 进入依赖收集阶段。让全局的Dep.target设置为Watcher本身,那么就是进入依赖收集阶段
        Dep.target = this;
        const obj = this.target;
        let value;

        // 只要能找,就一直找
        try {
            value = this.getter(obj);
        } finally {
            Dep.target = null;
        }

        return value;
    }

    run() {
        this.getAndInvoke(this.callback);
    }
    
    getAndInvoke(cb) {
        const value = this.get();

        if (value !== this.value || typeof value == 'object') {
            const oldValue = this.value;
            this.value = value;
            cb.call(this.target, value, oldValue);
        }
    }
};

function parsePath(str) {
    let segments = str.split('.');

    return (obj) => {
        for (let i = 0; i < segments.length; i++) {
            if (!obj) return;
            obj = obj[segments[i]]
        }
        return obj;
    };
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KaiSarH

如果觉得文章不错,可以支持下~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值