Vue 响应式原理深度解析
一、核心响应式系统架构
1. 响应式流程图解
数据变更 → 触发Setter → 通知Dep → 调用Watcher → 更新视图
2. 核心角色分工
- Observer:递归转换对象属性为响应式
- Dep (Dependency):管理依赖的容器
- Watcher:连接数据和视图的桥梁
- Scheduler:调度更新的队列系统
二、Vue2实现方案(基于Object.defineProperty)
1. 数据劫持实现
function defineReactive(obj, key) {
const dep = new Dep()
let val = obj[key]
Object.defineProperty(obj, key, {
get() {
if (Dep.target) {
dep.depend()
}
return val
},
set(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}
2. 数组方法重写
const arrayProto = Array.prototype
const arrayMethods = Object.create(arrayProto)
;['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(method => {
const original = arrayProto[method]
def(arrayMethods, method, function mutator(...args) {
const result