[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
vue2中是通过Object.definedProperty()来实现数组的劫持,
* 当vue初始化数据上的对象之后,在控制台打印可以看到有get和set方法,get是在读取属性值触发的函数,set是设置属性值触发的函数。 var
Book = {} var name = ''; Object.defineProperty(Book, 'name', { set: function
(value) { name = value; console.log('你取了一个书名叫做' + value); }, get: function () {
return '《' + name + '》' } }) Book.name = 'vue权威指南'; // 你取了一个书名叫做vue权威指南
console.log(Book.name); // 《vue权威指南》 -- set设置name属性值时触发,get读取name值时触发
* 实现简易版的数据绑定
*
通过Object.definedProperty()对属性设置一个set函数,当数据改变时就触发这个函数,自定义一些需要更新的方法放在set函数中即可实现data更新view
* 实现的思路
自定义双向绑定的实现过程
* 首先对数据进行劫持监听,设置一个监听器Observer,来监听所有的属性。-- 当属性发生变化时,告诉订阅者Watcher来查看是否需要更新。
* 此时订阅者Watcher接收到相应的属性变化,就可以执行对应的更新函数来更新视图。
* 之后我们需要一个指令解析器Compile,对每个节点元素进行扫描和解析,将相关指令对应初始化成一个订阅者Watcher,并替换模板数据或绑定相应的函数。
* 订阅者不是一个,是多个,这种情况下需要一个消息订阅器Dep来专门的收集订阅者们,然后在监听器Observer和订阅者Watcher之间进行统一的管理。
Observer、Watcher、Dep、Compile之间的关系图