Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(reactiviy): fix arrays don't reactive when mutate index #10464

Closed
wants to merge 8 commits into from
18 changes: 18 additions & 0 deletions packages/reactivity/__tests__/reactiveArray.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isReactive, reactive, toRaw } from '../src/reactive'
import { isRef, ref } from '../src/ref'
import { effect } from '../src/effect'
import { watchSyncEffect } from 'vue'

describe('reactivity/reactive/Array', () => {
test('should make Array reactive', () => {
Expand Down Expand Up @@ -99,6 +100,23 @@ describe('reactivity/reactive/Array', () => {
expect(fn).toHaveBeenCalledTimes(1)
})

test("should reactive when mutate array's index", () => {
const original = [1, 2, 3]
const observed = reactive(original)
const fn = vitest.fn(() => {
observed[0]
})
watchSyncEffect(fn)

delete observed[0]
expect(0 in observed).toBe(false)
expect(fn).toHaveBeenCalledTimes(2)

observed[0] = 2
expect(0 in observed).toBe(true)
expect(fn).toHaveBeenCalledTimes(3)
})

test('shift on Array should trigger dependency once', () => {
const arr = reactive([1, 2, 3])
const fn = vi.fn()
Expand Down
3 changes: 3 additions & 0 deletions packages/reactivity/src/reactiveEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export const MAP_KEY_ITERATE_KEY = Symbol(__DEV__ ? 'Map key iterate' : '')
*/
export function track(target: object, type: TrackOpTypes, key: unknown) {
if (shouldTrack && activeEffect) {
if (isArray(target) && typeof key === 'number') {
key = `${key}`
}
let depsMap = targetMap.get(target)
if (!depsMap) {
targetMap.set(target, (depsMap = new Map()))
Expand Down