vue2.0解析源码自定义实现vuejs(简单版)

vuejs基础版在页面中数据绑定使用

xxx.html中示例`
<div id="app">
    <p>
        {{count}}
    </p>
    <div v-text="text"></div>
    <div v-html="content"></div>
</div>
<script src="./vue.js"></script>
<script>
    const vm = new Vue({
        el: '#app',
        data: {
            count: 8888,
            content: '<span style="color:red">我说html</span>',
            text: '您好'
        }
    })

    setInterval(() => {
        // 代理过了 直接vm.count访问属性即可
        vm.count++
    }, 3000)
</script>

初始化的值:
在这里插入图片描述
5秒后修改的值:
在这里插入图片描述
vue.js自定义实现基础版

// 实现defineReactive数据响应式
function defineReactive(obj, key, val) {
    // 如果当前的值是obj那么继续递归
    // 解决多层嵌套问题
    observe(val)

    // 创建观察者
    // eslint-disable-next-line no-new
    const dep = new Dep()

    Object.defineProperty(obj, key, {
        get() {
            console.log('get', key)
            // 依赖收集
            Dep.target && dep.addDep(Dep.target)

            return val
        },
        set(newVal) {
            if (newVal !== val) {
                console.log('set', key, newVal)
                // 为了防止重新对已经绑定的值再次重新赋值
                observe(val)
                // 赋值
                val = newVal

                // 管家执行
                dep.notify()
            }
        }
    })
}

// 遍历obj所有的key 对所有属性绑定响应式
function observe(obj) {
    if (typeof obj !== 'object' || obj === null || !obj) {
        return
    }

    // eslint-disable-next-line no-new
    new Observe(obj)
}

// 根据传入的类型做响应式处理
class Observe {
    constructor(opts) {
        this.opts = opts

        if (Array.isArray(opts)) {
            // 数组响应式
        } else {
            // 对象响应式
            this.walk(opts)
        }
    }

    // 对象响应式
    walk(obj) {
        // 遍历所有的key,做响应式处理
        Object.keys(obj).forEach(key => {
            defineReactive(obj, key, obj[key])
        })
    }
}

// 代理掉this.$data
// this.count = 99设置值实际上就是访问的是this.$data.count的值
function proxy(vm) {
    Object.keys(vm.$data).forEach(key => {
        Object.defineProperty(vm, key, {
            get() {
                // 访问直接 this.+属性即可
                return vm.$data[key]
            },
            set(v) {
                vm.$data[key] = v
            }
        })
    })
}

/* Vue的实现 
1.对data选项做响应式处理
2.编译模板
*/
// eslint-disable-next-line no-unused-vars
class Vue {
    constructor(options) {
        this.$options = options
        this.$data = options.data

        console.log(this.$data)
        // 响应式处理
        observe(this.$data)

        // 代理一下this.$data
        proxy(this)

        // compile解析模板
        // eslint-disable-next-line no-new
        new Compile(options.el, this)
    }

    // $set方法转发defineReactive
    set(obj, key, val) {
        defineReactive(obj, key, val)
    }
}

// 进度https://www.bilibili.com/video/BV11L411t7XN?p=4&spm_id_from=pageDriver
class Compile {
    constructor(el, vm) {
        this.$vm = vm
        this.$el = document.querySelector(el)

        if (this.$el) {
            this.compile(this.$el)
        }
    }
    // 遍历el的字节点 判断他们的类型做对应处理
    compile(el) {
        const childNodes = el.childNodes
        childNodes.forEach(node => {
            // nodeType 1是元素 3是文本
            if (node.nodeType === 1) {
                // 元素
                // 处理指令和事件 v-text v-html v-xxx
                const attrs = node.attributes
                // 获取所有属性和值转为数组
                Array.from(attrs).forEach(attr => {
                    // 获取=左边指令名称
                    const attrName = attr.name
                    // 获取=右手边的值
                    const val = attr.value
                    // 有指令v-开头
                    if (attrName.startsWith('v-')) {
                        // 只取v-右边的部分 v-text取text
                        const prop = attrName.substring(2)
                        this[prop] && this[prop](node, val)
                    }
                })
            } else {
                // 文本
                // 判断是否是 {{xx}}表达式
                if (this.isInsert(node)) {
                    this.compileText(node)
                }
            }

            // 如果还有子级 那么递归
            if (node.childNodes) {
                this.compile(node)
            }
        })
    }

    // 是否是插值表达式正则
    isInsert(node) {
        const flag =
            node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
        return flag
    }

    update(node, prop, dir) {
        // 初始化
        const fn = this[dir + 'Update']
        fn && fn(node, this.$vm[prop])

        // 更新执行
        // eslint-disable-next-line no-new
        new Watcher(this.$vm, prop, function(val) {
            fn && fn(node, val)
        })
    }

    // {{xx}} 的文本解析和编译
    compileText(node) {
        // node.textContent = this.$vm[RegExp.$1]
        console.log(this.$vm[RegExp.$1])
        this.update(node, RegExp.$1, 'text')
        console.log('获取文本编译的值', node.textContent)
    }

    // v-text
    text(node, prop) {
        this.update(node, prop, 'text')
    }

    // v-tex更新dom
    textUpdate(node, val) {
        node.textContent = val
    }

    // v-html
    html(node, prop) {
        this.update(node, prop, 'html')
    }

    // v-html更新dom
    htmlUpdate(node, val) {
        node.innerHTML = val
    }
}

// 监听器:负责依赖更新
class Watcher {
    constructor(vm, key, updateCb) {
        this.vm = vm
        this.key = key
        this.updateCb = updateCb

        // 触发依赖收集 Dep是个全局变量
        Dep.target = this
        // 触发get
        // eslint-disable-next-line no-unused-expressions
        this.vm[this.key]
        // 触发完成清空
        Dep.target = null
    }

    // 执行更新 dep调用

    update() {
        // 执行实际更新操作
        this.updateCb.call(this.vm, this.vm[this.key])
    }
}

// 观察者
class Dep {
    constructor() {
        this.deps = []
    }

    // 所有的依赖收集 每一个this都收集
    addDep(dep) {
        this.deps.push(dep)
    }

    // 管家执行
    notify() {
        this.deps.forEach(dep => dep.update())
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

追逐梦想之路_随笔

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值