这篇文章主要介绍Proxy如何优化vue的数据监听机制问题,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
vue2.x中的实现
其本质是new Watcher(data, key, callback)
的方式,而在调用之前是先将data中的所有属性转化成可监听的对象, 其主要就是利用Object.defineProperty
,。
class Watcher{
constructor(data, key, cb){
}
}
//转换成可监听对象
function observe(data){
new Observer(data)
}
//修改数据的getter和setter
function defineReactive(obj, key){
let value = obj[key];
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get(){
return value;
},
set(newVal){
value = newVal
}
})
}
Observer的实现很简单
class Observer {
constructor(data){
this.walk(data);
}
walk(data){
for(var key in data) {
// 这里不考虑嵌套的问题,否则的话需要递归调用walk
defineReactive(data, key)
}
}
}
现在怎么将watcher和getter/setter联系起来,vue的方法是添加一个依赖类:Dep
class Watcher{
constructor(data, key, cb){
this.cb = cb;
Dep.target = this; //每次新建watcher的时候讲给target赋值,对target的管理这里简化了vue的实现
data[key];//调用getter,执行addSub, 将target传入对应的dep; vue的实现本质就是如此
}
}
class Dep {
constructor(){
this.subs = [];
}
addSub(sub){
this.subs.push(sub);
}
notify(){
this.subs.forEach(sub => sub.cb())
}
}
function defineReactive(obj, key){
let value = obj[key];
let dep = new Dep(); //每一个属性都有一个对应的dep,作为闭包保存
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get(){
dep.addSub(Dep.target)
Dep.target = null;
return value;
},
set(newVal){
value = newVal
dep.notify();
}
})
}
以上就是vue的思路,vue3之所以要从新实现,主要有这几个原因:
Object.defineProperty的性能开销。
defineReactive一开始就要对要监听的对象所有属性都执行一遍,因为传统方法要将一个对象转换成可监听对象,只能如此。
添加删除属性的问题。
还有一点就是这个模块被耦合到了vue里面,新版本可以单独作为一个库来使用。
然后我们来看看同样的功能采用Proxy会怎样实现。
Proxy的实现
将一个对象转换成Proxy的方式很简单,只需要作为参数传给proxy即可;
class Watcher {
constructor(proxy, key, cb) {
this.cb = cb;
Dep.target = this;
this.value = proxy[key];
}
}
class Dep {
constructor(){
this.subs = []
}
addSub(sub){
this.subs.push(sub);
}
notify(newVal){
this.subs.forEach(sub => {
sub.cb(newVal, sub.value);
sub.value = newVal;
})
}
}
const observe = (obj) => {
const deps = {};
return new Proxy(obj, {
get: function (target, key, receiver) {
const dep = (deps[key] = deps[key] || new Dep);
Dep.target && dep.addSub(Dep.target)
Dep.target = null;
return Reflect.get(target, key, receiver);
},
set: function (target, key, value, receiver) {
const dep = (deps[key] = deps[key] || new Dep);
Promise.resolve().then(() => {
dep.notify(value);
})
return Reflect.set(target, key, value, receiver);
}
});
}
var state = observe({x:0})
new Watcher(state, 'x', function(n, o){
console.log(n, o)
});
new Watcher(state, 'y', function(n, o){
console.log(n, o)
});
state.x = 3;
state.y = 3;
也许一开始我们只关心x和y,那么就不会对其他的属性做相应的处理,除非添加watcher,其他时间target都是null
以上是“Proxy如何优化vue的数据监听机制问题”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。