Skip to content

Commit 9c03a45

Browse files
authored
fix(reactivity): should trigger watchEffect when using set to change value of array length (#720)
1 parent bd198e7 commit 9c03a45

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/reactivity/set.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,16 @@ export function set<T>(target: any, key: any, val: T): T {
1515
`Cannot set reactive property on undefined, null, or primitive value: ${target}`
1616
)
1717
}
18-
if (isArray(target) && isValidArrayIndex(key)) {
19-
target.length = Math.max(target.length, key)
20-
target.splice(key, 1, val)
21-
return val
18+
if (isArray(target)) {
19+
if (isValidArrayIndex(key)) {
20+
target.length = Math.max(target.length, key)
21+
target.splice(key, 1, val)
22+
return val
23+
} else if (key === 'length' && (val as any) !== target.length) {
24+
target.length = val as any
25+
;(target as any).__ob__?.dep.notify()
26+
return val
27+
}
2228
}
2329
if (key in target && !(key in Object.prototype)) {
2430
target[key] = val

test/v3/reactivity/set.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { set, ref, watchEffect } from '../../../src'
2+
3+
describe('reactivity/set', () => {
4+
it('should trigger watchEffect when using set to change value of array length', () => {
5+
const arr = ref([1, 2, 3])
6+
const spy = jest.fn()
7+
watchEffect(
8+
() => {
9+
spy(arr.value)
10+
},
11+
{ flush: 'sync' }
12+
)
13+
14+
expect(spy).toHaveBeenCalledTimes(1)
15+
set(arr.value, 'length', 1)
16+
expect(arr.value.length).toBe(1)
17+
expect(spy).toHaveBeenCalledTimes(2)
18+
})
19+
})

0 commit comments

Comments
 (0)