实现简易版的 Vue

本文深入探讨Vue.js框架中数据响应化系统和模板编译的过程。通过`Observe`实现数据劫持,使用`Dep`管理依赖,并通过`Watcher`实例触发更新。同时,`Compile`方法解析DOM中的模板表达式,实现实时数据绑定。当输入元素绑定`v-model`时,建立双向数据绑定并监听输入变化。整个过程揭示了Vue.js响应式系统的核心机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Vue {
    constructor(options) {
        this.$data = options.data;
        
        // 进行数据劫持
        this.Observe(options.data);
        // 编译模版
        this.Compile(options.el);
    }

    Observe(data) {
        if (!data || typeof data !== 'object') {
            return;
        }
        const dep = new Dep();
        Object.keys(data).forEach(key => {
            let _that = this;
            let value = data[key];
            this.Observe(value);
            Object.defineProperty(data, key, {
                enumerable: true,
                configurable: true,
                get() {
                    // 收集依赖
                    Dep.target && dep.addSub(Dep.target);
                    return value;
                },
                set(newVal) {
                    value = newVal;
                    _that.Observe(newVal);
                    
                    dep.notify();
                }
            });
        })
    }

    Compile(el) {
        // const vm = this.$el;
        this.$el = document.querySelector(el);
        
        const fragment = document.createDocumentFragment();
        
        let childNode;
        while (childNode = this.$el.firstChild) {
            fragment.appendChild(childNode);
        }

        this.replace(fragment);

        this.$el.appendChild(fragment);
    }

    replace(node) {
        // 进行替换了
        const regMustache = /\{\{\s*(\S+)\s*\}\}/;
        // 文本子节点, 就是最里层了
        if (node.nodeType === 3) {
            const text = node.textContent;
            // console.log(text);
            const execResult = regMustache.exec(text);
            console.log(execResult);
            if (execResult) {
                const value = execResult[1].split('.').reduce((newObj, key) => newObj[key], this.$data);
                node.textContent = text.replace(regMustache, value);
                // 创建 watcher 实例
                console.log(1111);
                new Watcher(this, execResult[1], (newValue) => {
                    node.textContent = text.replace(regMustache, newValue);
                });
            }
            return;
        }
        
        if (node.nodeType === 1 && node.tagName.toUpperCase() == 'INPUT') {
            const attrs = Array.from(node.attributes);
            const findResult = attrs.find(attr => attr.name === 'v-model');
            if (findResult) {
                const expStr = findResult.value;
                const value = expStr.split('.').reduce((newObj, key) => newObj[key], this.$data);
                node.value = value;

                // 创建 watcher 实例
                new Watcher(this, expStr, (newValue) => {
                    node.value = newValue;
                })

                node.addEventListener('input', (e) => {
                    const keyArr = expStr.split('.');
                    const obj = keyArr.splice(0, keyArr.length - 1).reduce((newObj, key) => newObj[key], this.$data);
                    obj[keyArr[keyArr.length - 1]] = e.target.value;
                })
            }
        }
        // console.dir(node)
        node.childNodes.forEach(child => this.replace(child));
    }
}

class Dep {

    constructor() {
        this.subs = [];
    }

    // 收集依赖
    addSub(watcher) {
        this.subs.push(watcher);
    }
    
    // 通知
    notify() {
        this.subs.forEach(watcher => watcher.update());
    }
}

class Watcher {
    constructor(vm, key, callback) {
        this.vm = vm;
        this.key = key;
        this.callback = callback;

        Dep.target = this;
        key.split('.').reduce((newObj, key) => newObj[key], vm.$data);
        Dep.target = null;
    }

    update() {
        const value = this.key.split('.').reduce((newObj, k) => newObj[k], this.vm.$data);
        this.callback(value);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值