前言✨
以下都已vue2为基准
vue响应式原理完整流程图:
核心实现类
Vue:负责把data中的属性注入到Vue实例,并调用Observer类和Compiler类。
Observer:它的作用是给对象的属性添加 getter 和 setter,用于依赖收集和派发更新。
Watcher:观察者对象,将观察者实例挂载到Dep类中,数据发生变化的时候,调用回调函数更新视图。
Dep:用于收集当前响应式对象的依赖关系,每个响应式对象包括子对象都拥有一个 Dep 实例(里面 subs 是 Watcher 实例数组),当数据有变更时,会通过 dep.notify()通知各个 watcher。
Compiler:负责解析指令和插值表达式,页面的首次渲染,数据变化后,重新渲染视。
原理总结
当创建 Vue 实例时,vue 会遍历 data 选项的属性,利用 Object.defineProperty 为属性添加 getter 和 setter 对数据的读取进行劫持(getter 用来依赖收集,setter 用来派发更新),并且在内部追踪依赖,在属性被访问和修改时通知变化。 每个组件实例会有相应的 watcher 实例,会在组件渲染的过程中记录依赖的所有数据属性(进行依赖收集,还有 computed watcher,user watcher 实例),之后依赖项被改动时,setter 方法会通知依赖与此 data 的 watcher 实例重新计算(派发更新),从而使它关联的组件重新渲染。
一句话总结: vue.js 采用数据劫持结合发布-订阅模式,通过 Object.defineproperty 来劫持各个属性的 setter、getter在数据变动时发布消息给订阅者,触发响应的监听回调改变视图。
手动实现mini-vue💻
简易版vue响应式原理流程图:
index.html
<!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>mini-vue</title>
</head>
<body>
<div id="app">
父本文节点:{{str}}
<h2>子文本节点:{{str}}</h2>
{{num}}{{num}}
<button @click="btnClick">点击</button>
<input type="text" v-model="str" @input="input" />
</div>
<script src="vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
str: "mini-vue",
num: 123,
},
methods: {
btnClick() {
this.str = "修改后的值";
},
input() {},
},
});
</script>
</body>
</html
Vue类
/**
* 属性
* - $el:挂载的dom对象
* - $data: 数据
* - $options: 传入的属性
*
* 方法:
* - _proxyData 将数据转换成getter/setter形式
*
*/
class Vue {
constructor(options) {
// 1.保存 options的数据
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. 使用Obsever把data中的数据转为响应式 并监测数据的变化,渲染视图
new Observer(this.$data)
// 4. 调用 compiler类,解析指令和插值表达式
new Compiler(this)
}
_proxyData(data) {
// 1.遍历data对象的所有属性 进行数据劫持
Object.keys(data).forEach(key => {
/**
* 语法:Object.defineProperty(obj,property,descriptor)
* 参数一:obj
* 绑定属性的目标对象
* 参数二:property
* 绑定的属性名
* 参数三:descriptor
* 属性描述(配置),且此参数本身为一个对象
* 属性值1:value 设置属性默认值
* 属性值2:writable 设置属性是否能够修改
* 属性值3:enumerable 置属性是否可以枚举,即是否允许遍历
* 属性值4:configurable 设置属性是否可以删除或编辑
* 属性值5:get 获取属性的值
* 属性值6:set 设置属性的值
*
*/
// 2.把data中的属性,转换成vm的getter/setter
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get() {
return data[key]
},
set(newVal) {
if (newVal === data[key]) return
data[key] = newVal
}
})
})
}
}
Observer类
/**
* 功能
* - 把$data中的属性,转换成响应式数据
* - 如果$data中的某个属性也是对象,把该属性转换成响应式数据
* - 数据变化的时候,发送通知
*
* 方法:
* - walk(data) - 遍历data属性,调用defineReactive将数据转换成getter/setter
* - defineReactive(data, key, value) - 将数据转换成getter/setter
*
*/
class Observer {
constructor(data) {
this.walk(data)
}
// 遍历 data中的属性,把属性转换成响应式数据
walk(data) {
if (!data || typeof data !== 'object') {
return
}
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
// 定义响应式数据 obj=$data; key=data里面的key; value=key对应的值
defineReactive(obj, key, value) {
const that = this
// 负责收集依赖并发送通知
let dep = new Dep()
// 利用递归使深层(内部)属性转换成响应式数据
this.walk(value)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
// 收集依赖
Dep.target && dep.addSub(Dep.target)
return value
},
set(newValue) {
if (value === newValue) return
value = newValue
// 如果新设置的值为对象,也转换成响应式数据
that.walk(newValue)
// 发送通知
dep.notify()
}
})
}
}
Compiler类
/**
* 功能
* - 编译模板,解析指令/插值表达式
* - 负责页面的首次渲染
* - 数据变化后,重新渲染视图
*
* 属性
* - el -app元素
* - vm -vue实例
*
* 方法:
* - init(el) -编译入口
* - compileElement(node) -编译元素(指令)
* - compileText(node) 编译文本(插值)
* - isDirective(attrName) -(判断是否为指令)
* - update(node) -(执行对应指令方法)
* - modelUpdater(node) - (v-model方法)
* - isEvent(node) - (判断是否是事件)
*/
class Compiler {
constructor(vm) {
this.vm = vm
this.el = vm.$el
this.init(this.el)
}
init(el) {
const childNodes = el.childNodes
Array.from(childNodes).forEach(node => {
// 处理元素节点
if (node.nodeType === 1) {
this.compilerElement(node)
} else if (node.nodeType === 3) {
// 处理文本节点
this.compilerText(node)
}
if (node.childNodes.length) {
this.init(node)
}
})
}
// 编译文本节点,处理插值表达式
compilerText(node) {
const reg = /\{\{(.*?)\}\}/g
let value = node.textContent
if (reg.test(value)) {
node.textContent = value.replace(reg, (match, vmKey) => {
vmKey = vmKey.trim()
if (this.vm.hasOwnProperty(vmKey)) {
// 创建 Watcher对象,当数据改变时更新视图
new Watcher(this.vm, vmKey, (newValue) => {
// 仅替换{{}}里面的
const text = value.replace(match, newValue)
node.textContent = text
})
}
return this.vm[vmKey.trim()]
})
}
}
// 编译元素节点,处理指令
compilerElement(node) {
// 遍历所有属性节点
Array.from(node.attributes).forEach(attr => {
// 判断是否为 v-开头
let attrName = attr.name
if (this.isDirective(attrName)) {
// 为了更优雅的处理不同方法,减去指令中的 v-
attrName = attrName.substr(2)
const key = attr.value
this.update(node, key, attrName)
// 判断是否为事件 (这里仅简单判断@开头的事件)
} else if (this.isEvent(attrName)) {
let subAttrName = attrName.substr(1)
if (node.hasAttribute(attrName)) {
let vmKey = node.getAttribute(attrName).trim()
node.addEventListener(subAttrName, (event) => {
// 注意这里bing要绑定this.vm
this.eventFn = this.vm.$options.methods[vmKey].bind(this.vm)
this.eventFn(event)
})
}
}
})
}
// 执行对应指令的方法
update(node, key, attrName) {
let updateFn = this[attrName + 'Updater']
// 存在指令才执行对应方法
updateFn && updateFn.call(this, node, this.vm[key], key)
}
// v-model指令
modelUpdater(node, value, key) {
node.value = value
// 双向绑定
node.addEventListener('input', () => {
this.vm[key] = node.value
})
}
// 判断元素属性是否属于指令
isDirective(attrName) {
return attrName.startsWith('v-')
}
isEvent(attrName) {
return attrName.startsWith('@')
}
}
Watcher类
/**
* 功能
* - 生成观察者更新视图
* - 将观察者实例挂载到Dep类中
* - 数据发生变化的时候,调用回调函数更新视图
*
* 属性
* - vm: vue实例
* - key: 观察的键
* - cb: 回调函数
*
* 方法:
* - update()(更新视图)
*
*/
class Watcher {
constructor(vm, key, cb) {
// vue对象
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() {
const newValue = this.vm[this.key]
// 数据没有发生变化直接返回
if (this.oldValue === newValue) return
// 更新视图
this.cb(newValue)
new Compiler(this.vm)
}
}
Dep类
/**
* 功能
* - 收集观察者
* - 触发观察者
*
* 属性
* - subs: Array
* - target: Watcher
*
* 方法:
* - addSub(sub): 添加观察者
* - notify(): 触发观察者的update
*
*/
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
notify() {
this.subs.forEach(sub => {
sub.update()
})
}
}