前言
我们可能经常疑惑,Vue是怎么实现数据更新,视图变化。
视图变化,数据也能同样得到更新。
响应式原理
那么,我们来先看下面一张图:
整体流程:
- 我们得创建一个vue 对象。记录下参数 options 传递过来的选项,通过 _proxyData 把 data 中的属性注入Vue 实例中,就可以通过 this.xxx 调用了
- 创建 observer,作用是数据劫持,将 data 中属性,转换成 get,set。当数据变化的时候,触发变化,告诉 Dep: 我数据变化了,需要调用你的 notify 方法
- 而 Dep 的 notify 方法,又去调用 Watcher 的 updater 方法,也就是发送通知,告诉它,我的数据变了,你要更新视图了,此时 watcher 的 updater 方法就回去更新视图
- 当我们创建 watcher 对象的时候,也会把当前的 watcher 对象添加到 Dep 的 subs 数组中。也就是收集依赖,让 Dep 记录下来
- 在创建完 observer 的同时,也会创建 Compiler 对象,就是去解析指令,差值表达式等,在页面首次加载时,会调用 compiler 里面的方法更新视图。同时,还要去订阅数据变化(当数据变化时,Dep会通知Watcher),绑定更新视图(创建watcher时传递的回调函数,用它去更新视图)
- 总体来说:当页面首次加载时,是通过 Compiler 更新视图,当数据变化时,通过 Watcher 更新视图
创建 vue 对象
记录下参数 options,通过 _proxyData 把 data 中的属性 注入Vue实例中,就可以通过 this.xxx 调用了
class Vue {
constructor(options) {
// 1. 通过属性保存选项的数据
this.$options = options || {}
this.$data = options.data || {}
this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el
// 2. 把 data 中的成员转换成 getter 和 setter, 注入vue 实例中
this._proxyData(this.$data)
// 3. 调用 observer 对象,监听数据的变化
new Observer(this.$data)
// 4. 调用 compiler 对象,解析指令和差值表达式
new Compiler(this)
}
_proxyData (data) {
// 遍历 data 中所有属性
Object.keys(data).forEach(key => {
// 这里是注入到 vue 实例 中 方便后续使用
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get() {
return data[key]
},
set(newval) {
if (newval === data[key]) return
data[key] = newval
}
})
})
// 把 data 的属性注入到 vue 实例中
}
}
创建 observer
作用是数据劫持,将 data 中属性,转换成 get,set
class Observer {
constructor(data) {
this.walk(data)
}
walk(data) {
// 1. 判断data 是否是对象,保证代码健壮性
if (!data || typeof data !== 'object') return
// 2. 遍历 data 对象的所有属性
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
defineReactive(obj, key, val) {
const that = this
// 收集依赖,并发送通知
let dep = new Dep()
// 如果 val 是对象,则需要递归遍历
this.walk()
// 这里是注入到 this.$data 中
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
// 收集依赖
Dep.target && dep.addSub(Dep.target)
// 如果传递 obj[key] ,又会触发 get 方法,会造成栈溢出,因此要传递 val
return val
},
set(newval) {
if (newval === val) return
val = newval
that.walk()
// 发送通知
dep.notify()
}
})
}
}
创建Dep:
存储所有的观察者,并发送通知
class Dep {
constructor () {
// 存储所有的观察者
this.subs = []
}
// 添加观察者
addSub (sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
// 发送通知
notify() {
this.subs.forEach(sub => {
sub.update()
})
}
}
创建 Watcher 对象:
数据发生变化时,调用回调函数,更新视图
class Watcher {
constructor(vm, key, cb) {
this.vm = vm
// data 中的属性
this.key = key
// 回调函数,更新视图
this.cb = cb
// 把 watcher 对象记录到 Dep 类的静态属性 target
Dep.target = this
// 触发 get 方法,在 get 方法中会调用 addSub
this.oldValue = vm[key]
Dep.target = null // 需要重置,防止以后重新赋值
}
// 当数据发生变化时,更新视图
update() {
// 在调用 update 时,数据已经发生变化,因此 newValue 就是新值
let newValue = this.vm[this.key]
if (newValue === this.oldValue) return
this.cb(newValue)
}
}
创建 compiler:
编译模板,处理文本节点和元素节点
class Compiler {
constructor(vm) {
this.el = vm.$el
this.vm = vm
this.compile(this.el)
}
// 编译模板,处理文本节点和元素节点
compile(el) {
let childNodes = el.childNodes
Array.from(childNodes).forEach(node => {
if (this.isTextNode(node)) {
this.compileText(node)
} else if (this.isElementNode(node)) {
this.compileElement(node)
}
// 判断当前节点是否有子节点,有则递归
const flag = node.childNodes && node.childNodes.length
if (flag) this.compile(node)
})
}
// 编译元素节点,处理指令
compileElement(node) {
// 遍历所有的属性节点
Array.from(node.attributes).forEach(attr => {
// 判断是否为指令
let attrName = attr.name
if (this.isDirective(attrName)) {
attrName = attrName.substr(2) // 指令的后缀名称
const key = attr.value
this.update(node, key, attrName)
}
})
}
// 处理所有指令
update(node, key, attrName) {
const updateFn = this[attrName + 'Updater']
updateFn && updateFn.call(this, node, this.vm[key], key)
}
textUpdater(node, value, key) {
node.textContent = value
new Watcher(this.vm, key, newValue => {
node.textContent = newValue
})
}
modelUpdater(node, value, key) {
node.value = value
new Watcher(this.vm, key, newValue => {
node.value = newValue
})
// 双向绑定
node.addEventListener('input', () => {
console.log(value, node.value)
// 赋值当前表单中的值
this.vm[key] = node.value
})
}
// 处理文本节点,插值表达式
compileText(node) {
const reg = /\{\{(.+?)\}\}/
let value = node.textContent
if (reg.test(value)) {
const key = RegExp.$1.trim()
node.textContent = value.replace(reg, this.vm[key])
// 创建 Watcher 对象,当数据改变更新视图
new Watcher(this.vm, key, newValue => {
node.textContent = newValue
})
}
}
// 判断元素属性,是否为指令
isDirective (attrName) {
return attrName.startsWith('v-')
}
// 判断 是否为文本节点
isTextNode(node) {
return node.nodeType === 3
}
// 判断是否为元素节点
isElementNode(node) {
return node.nodeType === 1
}
}
双向绑定
- 有了上面的响应式原理的解释,那么双向绑定的原理就很好理解了
- 举个例子,主要针对表单,给表单绑定一个 input 事件,通过 node.value 获取视图上变更的值,重新赋值给 vue 对象上的属性值,再触发响应式机制,即可完成双向绑定