MVVM 设计模式,是由 MVC、MVP 等设计模式进化而来,M - 数据模型(Model),VM - 视图模型(ViewModel),V - 视图层(View)。MVVM 的外围是 ViewModel 层,它就像是一个中转站(value converter),负责转换 Model 中的数据对象来让数据变得更容易治理和应用,该层向上与视图层进行双向数据绑定,向下与 Model 层通过接口申请进行数据交互,起呈上启下作用。如下图所示:
Vue中的MVVM思维
应用 MVVM 设计模式的前端框架很多,其中渐进式框架 Vue 是典型的代表,深得宽广前端开发者的青眼。
从上图中能够看出MVVM次要分为这么几个局部:
- 模板编译(Compile)
- 数据劫持(Observer)
- 订阅-公布(Dep)
- 观察者(Watcher)
咱们来看一个 vue 的实例:
<!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>vue</title></head><body> <div id="app"> <p>{{ number }}</p> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> const VM = new Vue({ el: '#app', data: { number: 0 }, }) setInterval(() => { VM.number++ }, 1000) </script></body></html>
咱们对原理进行剖析一下:
- 首先
new Vue()
执行初始化,通过Observer
对data
上的属性执行响应式解决。也就是Object.defineProperty
对数据属性进行劫持。 - 通过
Compile
进行模板编译,对模板里动静绑定的数据,应用data
数据进行初始化。 - 在模板初始化时,在触发
Object.defineProperty
内的getter
时,创立更新函数和Watcher
类。 - 同一属性在模板中可能呈现屡次,就会创立多个
Watcher
,就须要Dep
来对立治理。 - 当数据发生变化时,找到属性对应的
dep
,告诉所有Watcher
执行更新函数。
创立Vue类
// 创立 Vue 类class Vue { constructor(options) { // 保留选项 this.$options = options; this.$data = options.data; // 响应式解决 observe(this.$data) // 将数据代理到实例上 proxyData(this, '$data') // 用数据和元素进行编译 new Compiler(options.el, this) }}// 代理数据的办法function proxyData (vm, sourceKey) { Object.keys(vm[sourceKey]).forEach(key => { Object.defineProperty(vm, key, { get () { return vm[sourceKey][key] }, set (newVal) { vm[sourceKey][key] = newVal } }) })}
下面代码创立了一个 Vue
类和 proxyData
办法,Vue
类接管 options
参数,外部调用 observe
办法对传入参数 options.data
数据,递归进行响应式解决。
应用 proxyData
办法把数据代理到实例上,让咱们获取和批改数据的时候能够间接通过 this
或 this.$data
, 如: this.number
或 this.$data.number
。
最初应用 Compiler
对模板进行编译,初始化动静绑定的数据。
模板编译(Compile)
// 模板编译class Compiler { constructor(el, vm) { this.$vm = vm; this.$el = document.querySelector(el); if (this.$el) { // 执行编译 this.compile(this.$el) } } compile (el) { // 遍历 el 树 const childNodes = el.childNodes; Array.from(childNodes).forEach((node) => { if (this.isElementNode(node)) { // 元素节点 // 编译元素节点的办法 this.compileElement(node) } else { // 文本节点 // 编译文本节点的办法 this.compileText(node) } // 如果还有子节点,持续递归 if (node.childNodes && node.childNodes.length > 0) { this.compile(node); } }) } // 判断是否是元素节点 isElementNode (node) { return node.nodeType === 1 } // 判断属性是否为指令 isDirective (attr) { return attr.indexOf('v-') === 0 } // 编译元素 compileElement (node) { // 遍历节点属性 const nodeAttrs = node.attributes Array.from(nodeAttrs).forEach((attr) => { const attrName = attr.name // 属性名 const exp = attr.value // 动静断定的变量名 //找到 v-xxx 的指令,如 v-text/v-html if (this.isDirective(attrName)) { let [, dir] = attrName.split("-") // 指令名 如 text/html // 调用指令对应得办法 this[dir] && this[dir](node, exp) } }) } // 编译文本 compileText (node) { let txt = node.textContent; // 获取文本节点的内容 let reg = /\{\{(.*)\}\}/; // 创立匹配 {{}} 的正则表达式 // 如果存在 {{}} 则应用 text 指令的办法 if (node.nodeType === 3 && reg.test(txt)) { this.update(node, RegExp.$1.trim(), 'text') } } update (node, exp, dir) { // 调用指令对应的更新函数 const callback = this[dir + 'Updater']; callback && callback(node, this.$vm[exp]) // 更新解决,创立 Watcher,保留更新函数 new Watcher(this.$vm, exp, function (val) { callback && callback(node, val) }) } // v-text text (node, exp) { this.update(node, exp, 'text') } textUpdater (node, value) { node.textContent = value } // v-html html (node, exp) { this.update(node, exp, 'html') } htmlUpdater (node, value) { node.innerHTML = value }}
编译过程中,以根元素开始,也就是实例化 Vue
时传入的 options.el
进行递归编译节点,应用 isElementNode
办法判断是文本节点还是元素节点。
如果是文本节点,正则匹配(双大括号){{ xxx }}
;应用 v-text
指令形式初始化读取数据。
若为元素节点,遍历属性,找到 v-text
或 v-html
,初始化动静绑定的数据。
在初始化数据时,创立 Watcher
和更新函数。
数据劫持(Observer)
function observe (obj) { if (typeof obj !== 'object' || obj == null) { return; } // 传入境来的对象做响应式解决 new Observer(obj)}function defineReactive (obj, key, val) { // 递归劫持数据 observe(val) // 创立与 key 对应的 Dep 治理相干的 Watcher const dep = new Dep(); //对数据进行劫持 Object.defineProperty(obj, key, { get () { // 依赖收集 Dep.target && dep.addDep(Dep.target) return val; }, set (newVal) { if (newVal !== val) { // 如果 newVal 为 Object ,就须要对其响应式解决 observe(newVal) val = newVal; // 告诉更新 dep.notify() } } })}class Observer { constructor(value) { this.value = value; if (typeof value === 'object') { this.walk(value) } } // 对象数据响应化 walk (obj) { Object.keys(obj).forEach(key => { defineReactive(obj, key, obj[key]) }) }}
下面代码,创立了 observe
和 defineReactive
办法,还有 Observer
类 。observe
办法用于类型判断。Observer
类收一个参数,若参数是 object 类型,调用 defineReactive
办法对其属性进行劫持。
在 defineReactive
办法中,通过 Object.defineProperty
对属性进行劫持。并对每个 key
创立 Dep
的实例,还记得模板编译时,对动静绑定的值,进行初始化的时候会创立 Watcher
吗?Watcher
内保留有对应的更新函数;defineReactive
中,数据被读取的时候,就会触发 getter
, getter
中就会把 Watcher
push 到对应的 Dep
中,这个过程就叫做依赖收集。当值产生扭转的时候,触发 setter
调用这个key
所对应的 Dep
内的 `notify
` 办法,告诉更新。
订阅-公布(Dep)
class Dep { constructor() { this.deps = [] } addDep (dep) { this.deps.push(dep) } notify () { this.deps.forEach(dep => dep.update()) }}
每个 key
都会创立一个 Dep
,每个 Dep
内都会有一个 deps
数组,用来同一治理这个 key
所对应的 Watcher
实例。addDep
办法用于增加订阅。notify
办法用于告诉更新。
观察者(Watcher)
// 观察者,保留更新函数。class Watcher { constructor(vm, key, updateFn) { this.vm = vm this.key = key this.updateFn = updateFn Dep.target = this // 在动态属性上保留以后实例 this.vm[this.key] // 触发数据劫持 get Dep.target = null // 在读取属性 触发get后,依赖收集结束,当初置空 } update () { this.updateFn.call(this.vm, this.vm[this.key]) }}
Watcher
类接管三个参数,Vue
的实例、 绑定的变量名 key
和 updateFn
更新办法。Watcher
在模板编译时被创立。咱们用 Dep.target
动态属性来保留以后的实例。被动触发一次响应式的 getter
, 使其实例被增加到 Dep
中,实现依赖收集,实现后,将动态属性 Dep.target
置空。
外部创立一个 update
更新办法。在 Dep
的 notify
办法告诉更新时被调用。
残缺代码
// 模板编译class Compiler { constructor(el, vm) { this.$vm = vm; this.$el = document.querySelector(el); if (this.$el) { // 执行编译 this.compile(this.$el) } } compile (el) { // 遍历 el 树 const childNodes = el.childNodes; Array.from(childNodes).forEach((node) => { if (this.isElementNode(node)) { // 元素节点 // 编译元素节点的办法 this.compileElement(node) } else { // 文本节点 // 编译文本节点的办法 this.compileText(node) } // 如果还有子节点,持续递归 if (node.childNodes && node.childNodes.length > 0) { this.compile(node); } }) } // 判断是否是元素节点 isElementNode (node) { return node.nodeType === 1 } // 判断属性是否为指令 isDirective (attr) { return attr.indexOf('v-') === 0 } // 编译元素 compileElement (node) { // 遍历节点属性 const nodeAttrs = node.attributes Array.from(nodeAttrs).forEach((attr) => { const attrName = attr.name // 属性名 const exp = attr.value // 动静断定的变量名 //找到 v-xxx 的指令,如 v-text/v-html if (this.isDirective(attrName)) { let [, dir] = attrName.split("-") // 指令名 如 text/html // 调用指令对应得办法 this[dir] && this[dir](node, exp) } }) } // 编译文本 compileText (node) { let txt = node.textContent; // 获取文本节点的内容 let reg = /\{\{(.*)\}\}/; // 创立匹配 {{}} 的正则表达式 // 如果存在 {{}} 则应用 text 指令的办法 if (node.nodeType === 3 && reg.test(txt)) { this.update(node, RegExp.$1.trim(), 'text') } } update (node, exp, dir) { // 调用指令对应的更新函数 const callback = this[dir + 'Updater']; callback && callback(node, this.$vm[exp]) // 更新解决,创立 Watcher,保留更新函数 new Watcher(this.$vm, exp, function (val) { callback && callback(node, val) }) } // v-text text (node, exp) { this.update(node, exp, 'text') } textUpdater (node, value) { node.textContent = value } // v-html html (node, exp) { this.update(node, exp, 'html') } htmlUpdater (node, value) { node.innerHTML = value }}// 创立 Vue 类class Vue { constructor(options) { // 保留选项 this.$options = options; this.$data = options.data; // 响应式解决 observe(this.$data) // 将数据代理到实例上 proxyData(this, '$data') // 用数据和元素进行编译 new Compiler(options.el, this) }}// 代理数据的办法function proxyData (vm, sourceKey) { Object.keys(vm[sourceKey]).forEach(key => { Object.defineProperty(vm, key, { get () { return vm[sourceKey][key] }, set (newVal) { vm[sourceKey][key] = newVal } }) })}function observe (obj) { if (typeof obj !== 'object' || obj == null) { return; } // 传入境来的对象做响应式解决 new Observer(obj)}function defineReactive (obj, key, val) { // 递归劫持数据 observe(val) // 创立与 key 对应的 Dep 治理相干的 Watcher const dep = new Dep(); //对数据进行劫持 Object.defineProperty(obj, key, { get () { // 依赖收集 Dep.target && dep.addDep(Dep.target) return val; }, set (newVal) { if (newVal !== val) { // 如果 newVal 为 Object ,就须要对其响应式解决 observe(newVal) val = newVal; // 告诉更新 dep.notify() } } })}class Observer { constructor(value) { this.value = value; if (typeof value === 'object') { this.walk(value) } } // 对象数据响应化 walk (obj) { Object.keys(obj).forEach(key => { defineReactive(obj, key, obj[key]) }) }}// 观察者,保留更新函数。class Watcher { constructor(vm, key, updateFn) { this.vm = vm this.key = key this.updateFn = updateFn Dep.target = this // 在动态属性上保留以后实例 this.vm[this.key] // 触发数据劫持 get Dep.target = null // 在读取属性 触发get后,依赖收集结束,当初置空 } update () { this.updateFn.call(this.vm, this.vm[this.key]) }}// 订阅-公布,治理某个key相干所有Watcher实例class Dep { constructor() { this.deps = [] } addDep (dep) { this.deps.push(dep) } notify () { this.deps.forEach(dep => dep.update()) }}
相干链接
[Vue(v2.6.14)源码解毒(预):手写一个简易版Vue]()
[Vue(v2.6.14)源码解毒(一):筹备工作]()
[Vue(v2.6.14)源码解毒(二):初始化和挂载(待续)]()
[Vue(v2.6.14)源码解毒(三):响应式原理(待续)]()
[Vue(v2.6.14)源码解毒(四):更新策略(待续)]()
[Vue(v2.6.14)源码解毒(五):render和VNode(待续)]()
[Vue(v2.6.14)源码解毒(六):update和patch(待续)]()
[Vue(v2.6.14)源码解毒(七):模板编译(待续)]()
如果感觉还对付的话,给个赞吧!!!也能够来我的 集体博客 逛逛