Skip to content

Commit

Permalink
fix(reactivity): should trigger watchEffect when using set to change …
Browse files Browse the repository at this point in the history
…value of array length (#720)
  • Loading branch information
hyf0 committed Jun 4, 2021
1 parent bd198e7 commit 9c03a45
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/reactivity/set.ts
Expand Up @@ -15,10 +15,16 @@ export function set<T>(target: any, key: any, val: T): T {
`Cannot set reactive property on undefined, null, or primitive value: ${target}`
)
}
if (isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
if (isArray(target)) {
if (isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
} else if (key === 'length' && (val as any) !== target.length) {
target.length = val as any
;(target as any).__ob__?.dep.notify()
return val
}
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
Expand Down
19 changes: 19 additions & 0 deletions test/v3/reactivity/set.spec.ts
@@ -0,0 +1,19 @@
import { set, ref, watchEffect } from '../../../src'

describe('reactivity/set', () => {
it('should trigger watchEffect when using set to change value of array length', () => {
const arr = ref([1, 2, 3])
const spy = jest.fn()
watchEffect(
() => {
spy(arr.value)
},
{ flush: 'sync' }
)

expect(spy).toHaveBeenCalledTimes(1)
set(arr.value, 'length', 1)
expect(arr.value.length).toBe(1)
expect(spy).toHaveBeenCalledTimes(2)
})
})

0 comments on commit 9c03a45

Please sign in to comment.