说到Vue源码必定会说到Vue的双向数据绑定,这里简单介绍下Vue响应式数据的实现,Vue内响应式的实现实际上时依据Object.defineProperty 与观察者模式实现的,但是很多人可能会将发布订阅模式与观察者模式搞混,这里也简单介绍两者的区别。
发布订阅模式
// 事件触发器
class EventEmitter {
constructor () {
// { 'click': [fn1, fn2], 'change': [fn] }
this.subs = Object.create(null)
}
// 注册事件
$on (eventType, handler) {
this.subs[eventType] = this.subs[eventType] || []
this.subs[eventType].push(handler)
}
// 触发事件
$emit (eventType) {
if (this.subs[eventType]) {
this.subs[eventType].forEach(handler => {
handler()
})
}
}
}
// 测试
let em = new EventEmitter()
em.$on('click', () => {
console.log('click1')
})
em.$on('click', () => {
console.log('click2')
})
em.$emit('click')
观察者模式
// 发布者-目标
class Dep {
constructor () {
// 记录所有的订阅者
this.subs = []
}
// 添加订阅者
addSub (sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
// 发布通知
notify () {
this.subs.forEach(sub => {
sub.update()
})
}
}
// 订阅者-观察者
class Watcher {
update () {
console.log('update')
}
}
// 测试
let dep = new Dep()
let watcher = new Watcher()
dep.addSub(watcher)
dep.notify()
实例化Vue的时候,我们需要将data中的数据转换为相应式数据,并注入到Vue实例上
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) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
enumerable: true, //可枚举
configurable: true, //可配置
get () {
return data[key]
},
set(newValue) {
if (newValue === data[key]) {
return
}
data[key] = newValue
}
})
})
}
}
Observer用于将data中的数据循环遍历全部转换为响应式数据,同时在触发getter时收集观察者,触发setter时触发Dep实例的notify方法更新视图
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) {
let that = this
// 负责收集依赖,并发送通知
let dep = new Dep()
// 如果val是对象,把val内部的属性转换成响应式数据
this.walk(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get () {
// 收集依赖 由Watcher中触发
Dep.target && dep.addSub(Dep.target)
return val
},
set (newValue) {
if (newValue === val) {
return
}
val = newValue
that.walk(newValue)
// 发送通知
dep.notify()
}
})
}
}
Compiler 主要用于响应式数据的渲染,解析指令和差值表达式
class Compiler {
constructor(vm) {
console.log(vm)
this.vm = vm
this.el = vm.$el
this.compile(this.el)
}
compile(el) {
let nodes = el.childNodes;
Array.from(nodes).forEach(node => {
if (this.isElementNode(node)) {
this.compileElement(node)
} else if (this.isTextNode(node)) {
this.compileText(node)
}
// 判断node节点,是否有子节点,如果有子节点,要递归调用compile
if (node.childNodes && node.childNodes.length) {
this.compile(node)
}
})
}
compileElement(node) {
let attrs = node.attributes;
let onReg = /^on/
Array.from(attrs).forEach(attr => {
if (this.isDirective(attr.name)) {
// v-text --> text
let attrName = attr.name.substr(2)
if (attr.name.startsWith('@')) {
attrName = attr.name.replace(/\@/, 'v-on:').substr(2)
}
let key = attr.value
if (onReg.test(attrName)) { //v-on
attrName = attrName.substr(3)
this.updateOn(node, key, attrName)
} else {// other
this.update(node, key, attrName)
}
}
})
}
update(node, key, attrName) {
let updateFn = this[attrName + 'Update']
updateFn && updateFn.call(this, node, this.vm[key], key)
}
//v-on事件
updateOn(node, key, attrName) {
let eventReg = /^\[(.*)\]$/
if (eventReg.test(attrName)) {
attrName = this.vm[RegExp.$1]
}
let oldEvent = attrName
new Watcher(this.vm, RegExp.$1, (newValue) => { //响应动态事件
node.removeEventListener(oldEvent, this.vm.$options.methods[key]) //清除上次事件
oldEvent = newValue; //记录上次注册的事件名
node.addEventListener(newValue, this.vm.$options.methods[key]) //注册事件
})
node.addEventListener(attrName, this.vm.$options.methods[key])//注册事件
}
textUpdate(node, value, key) {
node.textContent = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
modelUpdate(node, value, key) {
node.value = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.value = newValue
})
// 双向绑定
node.addEventListener('input', () => {
this.vm[key] = node.value
})
}
//v-html
htmlUpdate(node, value, key) {
console.log(node)
node.innerHTML = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.innerHTML = newValue
})
}
compileText(node) {
let reg = /\{\{(.+?)\}\}/
let value = node.textContent
if (reg.test(value)) {
let 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-') || attrName.startsWith('@')
}
// 判断节点是否是文本节点
isTextNode (node) {
return node.nodeType === 3
}
// 判断节点是否是元素节点
isElementNode (node) {
return node.nodeType === 1
}
}
class Dep {
constructor () {
// 存储所有的观察者
this.subs = []
}
// 添加观察者
addSub (sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
// 发送通知
notify () {
this.subs.forEach(sub => {
sub.update()
})
}
}
class Watcher {
constructor (vm, key, cb) {
this.vm = vm
// data中的属性名称
this.key = key
// 回调函数负责更新视图
this.cb = cb
// 把watcher对象记录到Dep类的静态属性target
Dep.target = this
// 触发Observer中的get方法,在get方法中会调用addSub
this.oldValue = vm[key]
Dep.target = null
}
// 当数据发生变化的时候更新视图
update () {
let newValue = this.vm[this.key]
if (this.oldValue === newValue) {
return
}
this.cb(newValue)
}
}
本文地址:https://blog.csdn.net/weixin_44213825/article/details/107292528
如对本文有疑问, 点击进行留言回复!!
蒲公英 · JELLY技术周刊 Vol.14: Vue 3 新特性详解
keepalived+haproxy+mycat+mysql高可用搭建配制
vue中子组件的created、mounted生命周期钩子中获取不到props中的值问题
网友评论