From 5fac65589b4455b98fd4e2f9eb3754f0acde97bb Mon Sep 17 00:00:00 2001 From: guaijie <30885718+guaijie@users.noreply.github.com> Date: Fri, 21 Feb 2020 18:38:07 +0800 Subject: [PATCH] fix(reactivity): should trigger all effects when array length is mutated (#754) --- packages/reactivity/__tests__/effect.spec.ts | 24 ++++++++++++++++++++ packages/reactivity/src/effect.ts | 5 ++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/reactivity/__tests__/effect.spec.ts b/packages/reactivity/__tests__/effect.spec.ts index 369cda98..3ce0748b 100644 --- a/packages/reactivity/__tests__/effect.spec.ts +++ b/packages/reactivity/__tests__/effect.spec.ts @@ -737,6 +737,30 @@ describe('reactivity/effect', () => { expect(fnSpy).toHaveBeenCalledTimes(1) }) + it('should trigger all effects when array lenght is set 0', () => { + const observed: any = reactive([1]) + let dummy, record + effect(() => { + dummy = observed.length + }) + effect(() => { + record = observed[0] + }) + expect(dummy).toBe(1) + expect(record).toBe(1) + + observed[1] = 2 + expect(observed[1]).toBe(2) + + observed.unshift(3) + expect(dummy).toBe(3) + expect(record).toBe(3) + + observed.length = 0 + expect(dummy).toBe(0) + expect(record).toBeUndefined() + }) + it('should handle self dependency mutations', () => { const count = ref(0) effect(() => { diff --git a/packages/reactivity/src/effect.ts b/packages/reactivity/src/effect.ts index f4cac6d4..03326426 100644 --- a/packages/reactivity/src/effect.ts +++ b/packages/reactivity/src/effect.ts @@ -174,8 +174,9 @@ export function trigger( } const effects = new Set() const computedRunners = new Set() - if (type === TriggerOpTypes.CLEAR) { - // collection being cleared, trigger all effects for target + if (type === TriggerOpTypes.CLEAR || (key === 'length' && isArray(target))) { + // collection being cleared or Array length mutation + // trigger all effects for target depsMap.forEach(dep => { addRunners(effects, computedRunners, dep) })