• 一看就懂的vue简版源码概述


    本文不会拆步骤对源码进行实现,只介绍vue原理及相关核心实现思想。在之前的四篇文章中已对vue进行响应实现。需要可阅读相关文章:

    ❄️ 理解Vue的设计思想

    MVVM框架的三要素:数据响应式、模板引擎及其渲染。
    在这里插入图片描述

    数据响应式:监听数据变化并在视图中更新

    • Object.defineProperty()
    • Proxy

    模版引擎:提供描述视图的模版语法

    • 插值:{{}}
    • 指令:v-bind,v-on,v-model,v-for,v-if

    渲染:如何将模板转换为html

    • 模板 => vdom => dom

    🌺数据响应式原理

    数据变更能够响应在视图中,就是数据响应式。vue2中利用 Object.defineProperty() 实现变更检测。

    1. 遍历需要响应化的对象
    2. 解决嵌套对象问题
    3. 解决赋的值是对象的情况
    4. 解决添加/删除了新属性无法检测的情况
    5. 解决数组数据的响应化

    ☀️Vue中的数据响应化

    在这里插入图片描述

    原理分析:

    1. newVue()首先执行初始化,对data执行响应化处理,这个过程发生在Observer中
    2. 同时对模板执行编译,找到其中动态绑定的数据,从data中获取并初始化视图,这个过程发生在 Compile中
    3. 同时定义一个更新函数和Watcher,将来对应数据变化时Watcher会调用更新函数
    4. 由于data的某个key在一个视图中可能出现多次,所以每个key都需要一个管家Dep来管理多个
      Watcher
    5. 将来data中数据一旦发生变化,会首先找到对应的Dep,通知所有Watcher执行更新函数

    在这里插入图片描述

    涉及类型介绍:

    1. Vue:框架构造函数
    2. Observer:执行数据响应化(分辨数据是对象还是数组)
    3. Compile:编译模板,初始化视图,收集依赖(更新函数、watcher创建)
    4. Watcher:执行更新函数(更新dom)
    5. Dep:管理多个Watcher,批量更新

    🐝编译Compile

    编译模板中vue模板特殊语法,初始化视图、更新视图
    在这里插入图片描述

    🦜依赖收集

    视图中会用到data中某key,这称为依赖。同一个key可能出现多次,每次都需要收集出来用一个
    Watcher来维护它们,此过程称为依赖收集。
    多个Watcher需要一个Dep来管理,需要更新时由Dep统一通知。
    看下面案例,理出思路:

     
    new Vue({
        template:
    		`<div> 
    			<p>{{name1}}p>
    		    <p>{{name2}}p>
    			<p>{{name1}}p> 
    		<div>`,
    	data: {
    			name1: 'name1',
    			name2: 'name2' 
    		}
    	});
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    实现思路

    1. defineReactive时为每一个key创建一个Dep实例
    2. 初始化视图时读取某个key,例如name1,创建一个watcher1
    3. 由于触发name1的getter方法,便将watcher1添加到name1对应的Dep中
    4. 当name1更新,setter触发时,便可通过对应Dep通知其管理所有Watcher更新

    👗完整代码

    // 数组响应式
    const oldArrayProperty = Array.prototype
    const arrayProto = Object.create(oldArrayProperty)
    
    const methodsToPatch = ['push', 'pop', 'unshift', 'shift', 'sort', 'splice', 'reverse']
    methodsToPatch.forEach(methodName => {
      Object.defineProperty(arrayProto, methodName, {
        value () {
          console.log('you change the array')
          oldArrayProperty[methodName].apply(this, arguments)
        }
      })
    })
    
    // 给一个obj定义一个响应式的属性
    function defineReactive (obj, key, val) {
      // 递归
      // val如果是个对象,就需要递归处理
      observe(val)
      const dep = new Dep()
      Object.defineProperty(obj, key, {
        get () {
          Dep.target && dep.addDep(Dep.target)
          return val
        },
        set (newVal) {
          if (newVal !== val) {
            console.log('set', key, val)
            val = newVal
            // 新值如果是对象,仍然需要递归遍历处理
            observe(newVal)
            dep.notify()
            // 暴力的写法,让一个人干事指挥所有人动起来
            // watchers.forEach(watch => {
            //   watch.update()
            // })
          }
        }
      })
    }
    
    // 遍历响应式处理
    function observe (obj) {
      if (typeof obj !== 'object' || obj == null) {
        return obj
      }
    
      new Observer(obj)
    }
    
    class Observer {
      constructor (obj) {
        // 判断传入obj类型,做相应处理
        if (Array.isArray(obj)) {
          Object.setPrototypeOf(obj, arrayProto)
          //   对数组内部元素执行响应式
          const keys = Object.keys(obj)
          keys.forEach(key => observe(obj[key]))
        } else {
          this.walk(obj)
        }
      }
    
      walk (obj) {
        Object.keys(obj).forEach((key) => {
          defineReactive(obj, key, obj[key])
        })
      }
    }
    
    // 能够将传入对象中的所有key代理到指定对象上
    function proxy (vm) {
      Object.keys(vm.$data).forEach((key) => {
        Object.defineProperty(vm, key, {
          get () {
            return vm.$data[key]
          },
          set (v) {
            vm.$data[key] = v
          }
        })
      })
    }
    
    class MVue {
      constructor (options) {
        // 保存options
        this.$options = options
        this.$data = options.data
        this.$methods = options.methods
    
        // 将data进行响应式处理
        observe(this.$data)
    
        // 代理
        proxy(this)
    
        // 编译
        new Compile(options.el, this)
      }
    }
    
    class Compile {
      constructor (el, vm) {
        this.$vm = vm
        this.$el = document.querySelector(el)
    
        if (this.$el) {
          this.compile(this.$el)
        }
      }
    
      compile (node) {
        // 找到该元素的子节点
        const childNodes = node.childNodes
        // childNodes是类数组对象
        Array.from(childNodes).forEach(n => {
          // 判断类型
          if (this.isElment(n)) {
            this.compileElement(n)
            // 递归
            if (n.childNodes.length > 0) {
              this.compile(n)
            }
          } else if (this.isInter(n)) {
            // 动态插值表达式  编译文本
            this.compileText(n)
          }
        })
      }
    
      isElment (node) {
        return node.nodeType === 1
      }
    
      isInter (n) {
        return n.nodeType === 3 && /\{\{(.*)\}\}/.test(n.textContent)
      }
    
      isDir (attrName) {
        return attrName.startsWith('m-')
      }
    
      isEvent (attrName) {
        return attrName.startsWith('@')
      }
    
      // 编译元素:遍历它的所有属性,看是否k-开头指令,或者@事件
      compileElement (node) {
        const attrs = node.attributes
        Array.from(attrs).forEach(attr => {
          // m-text="XXX"
          // name = m-text, value=xxx
          const attrName = attr.name
          const exp = attr.value
          // 是指令
          if (this.isDir(attrName)) {
            // 执行特定指令处理函数
            const dir = attrName.substring(2)
            this[dir] && this[dir](node, exp)
          } else if (this.isEvent(attrName)) {
            const event = attrName.substring(1)
            // node['on' + event] = this.$vm.$methods[exp]
            // 通过bind改变this指向为vm实例,以便方法内部访问vm.data中的数据
            node.addEventListener(event, this.$vm.$methods[exp].bind(this.$vm))
          }
        })
      }
    
      update (node, exp, dir) {
        // 第一步: 初始化值
        const fn = this[dir + 'Updater']
        fn && fn(node, this.$vm[exp])
        // 第二步: 更新
        new Watcher(this.$vm, exp, val => {
          fn && fn(node, val)
        })
      }
    
      compileText (n) {
        // 获取表达式
        // n.textContent = this.$vm[RegExp.$1]
        // n.textContent = this.$vm[RegExp.$1.trim()]
        this.update(n, RegExp.$1.trim(), 'text')
      }
    
      text (node, exp) {
        this.update(node, exp, 'text')
        // node.textContent = this.$vm[exp] || exp
      }
    
      textUpdater (node, val) {
        node.textContent = val
      }
    
      html (node, exp) {
        this.update(node, exp, 'html')
        // node.innerHTML = this.$vm[exp]
      }
    
      htmlUpdater (node, val) {
        node.innerHTML = val
      }
    
      model (node, exp) {
        node.value = this.$vm[exp]
        node.addEventListener('input', (e) => {
          this.$vm[exp] = e.target.value
        })
      }
    }
    
    // // 监听器:负责依赖更新
    // const watchers = []
    // class Watcher {
    //   constructor (vm, key, updateFn) {
    //     this.vm = vm
    //     this.key = key
    //     this.updateFn = updateFn
    
    //     watchers.push(this)
    //   }
    
    //   update () {
    //     // 绑定作用域为this.vm,并且将this.vm[this.key]作为值传进去
    //     this.updateFn.call(this.vm, this.vm[this.key])
    //   }
    // }
    
    // 监听器:负责依赖更新
    class Watcher {
      constructor (vm, key, updateFn) {
        this.vm = vm
        this.key = key
        this.updateFn = updateFn
    
        // 触发依赖收集
        Dep.target = this
        // 触发一下get
        this.vm[this.key]
        Dep.target = null
      }
    
      update () {
        // 绑定作用域为this.vm,并且将this.vm[this.key]作为值传进去
        this.updateFn.call(this.vm, this.vm[this.key])
      }
    }
    
    class Dep {
      constructor () {
        this.deps = []
      }
    
      addDep (dep) {
        this.deps.push(dep)
      }
    
      notify () {
        this.deps.forEach(dep => dep.update())
      }
    }
    
    
    • 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
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263

    测试代码:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <div id="app">
            <p>{{ counter }}</p>
            <p m-text="测试"></p>
            <p m-text="counter"></p>
            <p m-html="desc"></p>
            <p @click="test">点击我</p>
            <input m-model="desc" />
        </div>
    </body>
    <script src="./index.js"></script>
    <script>
        const app = new MVue({
                el: '#app',
                data: {
                    counter: 1,
                    desc: 'super wanan',
                    name: 'wanan',
                    arr: [{
                        name: 1,
                        arr: [12]
                    }]
                },
                methods: {
                    test() {
                        this.counter++;
                        console.log('进入了', this.counter)
                        this.arr.push(2)
                        this.arr[0].arr.push(2)
                        console.log('进入了', this.arr)
                    }
                },
            })
            // setInterval(() => {
            //     app.counter++
            // }, 1000)
    </script>
    
    </html>
    
    • 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
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  • 相关阅读:
    [附源码]JAVA毕业设计互联网保险网站(系统+LW)
    Adaptive AUTOSAR Technology Sharing
    WPF中DataContext作用
    screenfull全屏、退出全屏、指定元素全屏的使用步骤
    el-select的某一项选中后显示id
    1、Flowable基础
    大学解惑06 - 要求输入框内只能输入2位以内小数,怎么做?
    javaweb-SMBMS
    【AUTOSAR-CAN-3】COM 模块详解
    iOS上架app store详细教材
  • 原文地址:https://blog.csdn.net/weixin_43867717/article/details/126749738