From 6b7b452a561774ac7107b668442440d92b306b3b Mon Sep 17 00:00:00 2001 From: dj <1042039504@qq.com> Date: Thu, 5 Feb 2026 22:36:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(ref):=20=E5=AE=9E=E7=8E=B0=20ref=20?= =?UTF-8?q?=E5=80=BC=E5=8F=98=E5=8C=96=E6=A3=80=E6=B5=8B=E5=92=8C=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E8=A7=A6=E5=8F=91=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 shared 包中新增 hasChanged 函数用于比较值是否发生变化 - 修改 RefImpl 类添加 _rawValue 属性存储原始值 - 实现 ref setter 中的值变化检测逻辑 - 添加 triggerRefValue 函数用于触发 ref 依赖更新 - 优化 ref 的 getter 和 setter 方法实现响应式更新 --- packages/reactivity/src/ref.ts | 21 +++++++++++++++++++-- packages/shared/src/index.ts | 8 ++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index c7c392f..6194830 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -1,6 +1,7 @@ import { createDep, Dep } from './dep' import { toReactive } from './reactive' -import { activeEffect, track, trackEffects } from './effect' +import { activeEffect, triggerEffects, trackEffects } from './effect' +import { hasChanged } from '@vue/shared' export interface Ref { value: T @@ -17,20 +18,36 @@ function createRef(rawValue: unknown, shallow: boolean) { } class RefImpl { private _value: T + private _rawValue: T public dep?: Dep = undefined public readonly __v_isRef = true constructor( value: T, public readonly __v_isShallow: boolean ) { + this._rawValue = value this._value = __v_isShallow ? value : toReactive(value) } get value() { trackRefValue(this) return this._value } - set value(newValue) {} + set value(newValue) { + if (hasChanged(newValue, this._rawValue)) { + this._rawValue = newValue + this._value = toReactive(newValue) + triggerRefValue(this) + } + } } +//触发依赖 +export function triggerRefValue(ref) { + if (ref.dep) { + triggerEffects(ref.dep) + } +} + +//收集依赖 export function trackRefValue(ref) { if (activeEffect) { trackEffects(ref.dep || (ref.dep = createDep())) diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index f020f62..c61acce 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3,3 +3,11 @@ export const isArray = Array.isArray export const isObject = (val: unknown) => val !== null && typeof val === 'object' + +/** + * 对比两个数据是否发生改变 + * @param value + * @param oldValue + */ +export const hasChanged = (value: any, oldValue: any): boolean => + !Object.is(value, oldValue)