Vue源码探秘之指令和生命周期

231 阅读2分钟

一、项目环境搭建

项目环境和之前的一样,由webpack和webpack-dev-server搭建而成。

// package.json
{
  "name": "study-snabbdom",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "webpack": "^5.11.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

// webpack.config.js
// 从https://www.webpackjs.com/官网照着配置
const path = require('path');

module.exports = {
    // 入口
    entry: './src/index.js',
    // 出口
    output: {
        // 虚拟打包路径,就是说文件夹不会真正生成,而是在8080端口虚拟生成
        publicPath: 'xuni',
        // 打包出来的文件名,不会真正的物理生成
        filename: 'bundle.js'
    },
    devServer: {
        // 端口号
        port: 8080,
        // 静态资源文件夹
        contentBase: 'www'
    }
};

二、Vue类的创建

// src/index.js
import Vue from './Vue.js';

window.Vue = Vue;

// src/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() {
        var self = this;
        Object.keys(this._data).forEach(key => {
            Object.defineProperty(self, key, {
                get: () => {
                    return self._data[key];
                },
                set: (newVal) => {
                    self._data[key] = newVal;
                }
            });
        });
    }

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

三、Fragment的生成

// src/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);
        }
    }
    node2Fragment(el) {
        var fragment = document.createDocumentFragment();

        var child;
        // 让所有DOM节点,都进入fragment
        while (child = el.firstChild) {
            fragment.appendChild(child);
        }
        return fragment;
    }
    compile(el) {
        // console.log(el);
        // 得到子元素
        var childNodes = el.childNodes;
        var self = this;

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

        childNodes.forEach(node => {
            var 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结构看做字符串,而是真正的属性列表
        var nodeAttrs = node.attributes;
        var self = this;

        // 类数组对象变为数组
        [].slice.call(nodeAttrs).forEach(attr => {
            // 这里就分析指令
            var attrName = attr.name;
            var value = attr.value;
            // 指令都是v-开头的
            var 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;
                    });
                    var v = self.getVueVal(self.$vue, value);
                    node.value = v;

                    // 添加监听
                    node.addEventListener('input', e => {
                        var 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) {
        var val = vue;
        exp = exp.split('.');
        exp.forEach(k => {
            val = val[k];
        });

        return val;
    }

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

    }
}


四、初始数据的响应式和watch

把之前学的手写响应式代码拿过来

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

// src/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]);
        }
    }
};


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

// src/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();
        }
    });
};


// src/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);
});


// src/Dep.js
var 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();
        }
    }
};


// src/Watcher.js
import Dep from "./Dep";

var 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;
        var 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) {
    var segments = str.split('.');

    return (obj) => {
        for (let i = 0; i < segments.length; i++) {
            if (!obj) return;
            obj = obj[segments[i]]
        }
        return obj;
    };
}

<!-- www/index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        你好{{b.m.n}}
        <br />
        <input type="text" v-model="b.m.n">
    </div>
    <button onclick="add()">按我加1</button>

    <script src="/xuni/bundle.js"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                a: 10,
                b: {
                    m: {
                        n: 7
                    }
                }
            },
            watch: {
                a() {
                    console.log('a改变啦');
                }
            },
            created() {

            },
            update() {

            }
        });

        console.log(vm)

        function add() {
            vm.b.m.n++;
        }
    </script>
</body>

</html>