Vue2 源码从零详解系列文章, 还没有看过的同学可能需要看一下之前的,vue.windliang.wang/
场景
import { observe } from "./reactive";
import { initWatch } from "./state";
const options = {
data: {
first: {
text: "hello",
},
title: "liang",
},
watch: {
"first.text": function (newVal, oldVal) {
console.log("收到变化", newVal, oldVal);
},
title(newVal, oldVal) {
console.log("收到变化", newVal, oldVal);
},
},
};
observe(options.data);
initWatch(options.data, options.watch);
options.data.first.text = "changeText";
options.data.title = "changeTitle";
相信大家在 Vue
中一定写过 watch
,用来监听 data
中的数据变化,回调函数会接收到新值和旧值。
这篇文章来实现 initWatch
,因为需要用到 data
所以要把 data
传入,还有就是 watch
也传入。
实现思路
之前的文章我们实现了一个 Watcher
类。
export default class Watcher {
constructor(Fn, options) {
this.getter = Fn;
this.depIds = new Set(); // 拥有 has 函数可以判断是否存在某个 id
this.deps = [];
this.newDeps = []; // 记录新一次的依赖
this.newDepIds = new Set();
this.id = ++uid; // uid for batching
// options
if (options) {
this.sync = !!options.sync;
}