实现一个简单的mvvm框架

261 阅读3分钟

一.MVVM框架三要素:数据响应式,模板引擎及其渲染

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

  1. object.defineProperty
  2. proxy

2.模板引擎:提供描述视图的模板语法

  1. 插值:{{}}
  2. 指令:v-bind,v-on,v-model,v-for,v-if

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

  1. 模板 => vdom => dom
 vue add vuex

二.数据响应式原理

  1. 简单实现
const obj = {}

function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log(`get ${key}:${val}`);
      return val
    },
    set(newVal) {
      if (newVal !== val) {
        console.log(`set ${key}:${newVal}`);
        val = newVal
      }
    }
  })
}

defineReactive(obj, 'foo', 'foo')
obj.foo
obj.foo = 'foooooooooooo'
  1. 结合视图
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script>
  const obj = {}
  function defineReactive(obj, key, val) {
    Object.defineProperty(obj, key, {
        get() {
          console.log(`get ${key}:${val}`);
          return val
        },
        set(newVal) {
          if (newVal !== val) {
            val = newVal
            update()
          }
        }
      }
    )
  }
  
  defineReactive(obj, 'foo', '')
  
  obj.foo = new Date().toLocaleTimeString()
  
  function update() {
    app.innerText = obj.foo
  }
  
  setInterval(() => {
    obj.foo = new Date().toLocaleTimeString()
  }, 1000);
  
</script>
</body>
</html>
  1. 遍历需要响应化的对象
// 对象响应化:遍历每个key,定义getter、setter
function observe(obj) {
  // 判断obj类型必须是对象
  if (typeof obj !== 'object' || obj == null) {
    return
  }

  Object.keys(obj).forEach(key => defineReactive(obj, key, obj[key]))
}
  1. 解决嵌套对象问题
function defineReactive(obj, key, val) {
  observe(val)
  Object.defineProperty(obj, key, {
//...
  1. 解决赋的值是对象的情况
obj.baz = {a:1}
obj.baz.a = 10 // no ok
set(newVal) {
 if (newVal !== val) {
   console.log('set', newVal);
   // 解决赋的值是对象的情况
   observe(newVal)
   val = newVal
 }
}
  1. 如果添加/删除了新属性无法检测
obj.dong = 'dong' 
obj.dong // 并没有get信息
//写一个set方法并对数据做响应化处理
function set(obj, key, val) {
 defineReactive(obj, key, val)
}
// 测试
set(obj, 'dong', 'dong')
obj.dong

三.应用到vue中的数据响应化

原理分析

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

涉及类型介绍

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

源码实现

步骤一:框架构造函数:执行初始化

  1. 创建vue实例
// 创建Vue实例
class Vue {
  constructor(options) {
    // 保存选项
    this.$options = options

    this.$data = options.data

    // 响应化处理
    observe(this.$data)

    // 代理
    proxy(this)

    // 编译
    new Compile('#app', this)
  }
}
  1. 执行初始化,对data执行响应化处理
// 对象响应式处理
function observe(obj) {
  // 判断obj类型必须是对象
  if (typeof obj !== 'object' || obj == null) {
    return
  }

  // 每一个响应式对象,伴生一个Observer实例
  new Observer(obj)
}

// 创建Observer
class Observer {
  constructor(value) {
    this.value = value

    // 判断value是obj还是数组
    this.walk(value)
  }

  walk(obj) {
    Object.keys(obj).forEach(
      key => defineReactive(obj, key, obj[key]))
  }
}
 
function defineReactive(obj, key, val) {
    //执行的操作跟前面一样
}
  1. 为$data做代理
// 将$data中的key代理到KVue实例上
function proxy(vm) {
  Object.keys(vm.$data).forEach(key => {
    Object.defineProperty(vm, key, {
      get() {
        return vm.$data[key]
      },
      set(v) {
        vm.$data[key] = v
      }
    })
  })
}

步骤二:编译---compile

  1. 创建一个compile实例
class Compile {
  constructor(el, vm) {
    this.$vm = vm

    this.$el = document.querySelector(el)

    // 编译模板
    if (this.$el) {
      this.compile(this.$el)
    }
  }
  
    // 递归遍历el
    compile(el) {
    el.childNodes.forEach(node => {
      // 判断其类型
      if (this.isElement(node)) {
        // console.log('编译元素', node.nodeName);
        this.compileElement(node)
      } else if (this.isInter(node)) {
        // console.log('编译插值表达式', node.textContent);
        this.compileText(node)
      }

      if (node.childNodes) {
        this.compile(node)
      }
    })
  }
  
    // 插值文本编译
  compileText(node) {
    // 获取匹配表达式
    // node.textContent = this.$vm[RegExp.$1]
    this.update(node, RegExp.$1, 'text')
  }
  
  // 获取节点属性
  compileElement(node) {
    const nodeAttrs = node.attributes
    Array.from(nodeAttrs).forEach(attr => {
      // v-xxx="aaa"
      const attrName = attr.name // v-xxx
      const exp = attr.value // aaa
      // 判断这个属性类型
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2)
        // 执行指令
        this[dir] && this[dir](node, exp)
      } 
      
      else if(attrName.startWith('@')){
        // 
        
      }
    })
  }
  
   // 文本指令
  text(node, exp) {

    this.update(node, exp, 'text')
  }

  html(node, exp) {

    this.update(node, exp, 'html')
  }
  
    // 所有动态绑定都需要创建更新函数以及对应watcher实例
  update(node, exp, dir) {
    // textUpdater()
    // 初始化
    const fn = this[dir + 'Updater']
    fn && fn(node, this.$vm[exp])

    // 更新: 
    new Watcher(this.$vm, exp, function (val) {
      fn && fn(node, val)
    })
  }
   textUpdater(node, value) {
    node.textContent = value
  }

  htmlUpdater(node, value) {
    node.innerHTML = value
  }
  
    // 元素
  isElement(node) {
    return node.nodeType === 1
  }

  // 判断是否是插值表达式{{xx}}
  isInter(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
  }

  isDirective(attrName) {
    return attrName.indexOf('v-') === 0
  }
}

步骤三:依赖收集

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

实现思路

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

代码解析

  1. 创建Watcher
// Watcher: 界面中的一个依赖对应一个Watcher
class Watcher {
  constructor(vm, key, updateFn) {
    this.vm = vm
    this.key = key
    this.updateFn = updateFn

    // 读一次数据,触发defineReactive里面的get()
    Dep.target = this
    this.vm[this.key]
    Dep.target = null
  }

  // 管家调用
  update() {
    // 传入当前的最新值给更新函数
    this.updateFn.call(this.vm, this.vm[this.key])
  }
}
  1. 编写更新函数、实例化watcher
// 调用update函数执插值文本赋值
compileText(node) {
  // console.log(RegExp.$1);
  // node.textContent = this.$vm[RegExp.$1];
  this.update(node, RegExp.$1, 'text')
}
text(node, exp) {
  this.update(node, exp, 'text')
}
html(node, exp) {
  this.update(node, exp, 'html')
}
update(node, exp, dir) {
  const fn = this[dir + 'Updater']
  fn && fn(node, this.$vm[exp])
  new Watcher(this.$vm, exp, function (val) {
    fn && fn(node, val)
  })
}
textUpdater(node, val) {
  node.textContent = val;
}
htmlUpdater(node, val) {
  node.innerHTML = val
}
  1. 声明Dep
 
class Dep {
  constructor() {
    this.deps = []
  }

  addDep(dep) {
    this.deps.push(dep)
  }

  notify() {
    this.deps.forEach(dep => dep.update());
  }
}
  1. 创建watcher时触发getter
class Watcher {
  constructor(vm, key, updateFn) {
    // 读一次数据,触发defineReactive里面的get()
    Dep.target = this
    this.vm[this.key]
    Dep.target = null
  }
}
  1. 依赖收集,创建Dep实例
defineReactive(obj, key, val){
  this.observe(val);
  const dep = new Dep()
  Object.defineProperty(obj, key, {
    get() {
      Dep.target && dep.addDep(Dep.target);
      return val

    },
    set(newVal) {
      if (newVal === val) return
      dep.notify()
    }
  })
}