【学习】vue监听属性
前言
文章基于响应系统。如没有相关概念,建议看完在继续。
watch
/*** @description 监听响应式数据* @param {Proxy | Function} source* @param {Function} cb* @param {Object} options*/
const watch = (source, cb, options = {}) => {let getter;if (typeof source === "function") {getter = source;} else {getter = () => traverse(source)}let oldValue, newValue;let cleanup;/*** @description 当前副作用函数过期执行* @param {Function} fn*/const onInvalidate = (fn) => {cleanup = fn;}const job = () => {if (cleanup) {cleanup()}newValue = effectFn();cb(newValue, oldValue, onInvalidate);oldValue = newValue;}const effectFn = effect(() => getter(), {lazy: true,scheduler() {job()}})if (options.immediate) {job()} else {oldValue = effectFn()}
}
index.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>toy</title></head><body></body><script type="module">import { reactive, effect, computed, watch } from "./reactive/index.js";const data = reactive({ foo: 1, bar: 4 });const sum = computed(() => data.foo + data.bar);watch(() => sum.value,(newValue, oldValue) => {console.log(newValue, oldValue, "数据变化了");},{immediate: true,});data.foo++;</script>
</html>