Skip to content

Commit e47b1e5

Browse files
pkaminskiyyx990803
authored andcommitted
Allow named properties on reactive arrays. (vuejs#5216)
* Allow named properties on reactive arrays. * Remove semicolons to comport with style guide. * Pacify flow type checking. Without the cast to any, flow complains that Array doesn't have an __ob__ property. This appears to be an instance of this issue: facebook/flow#1330
1 parent 70db229 commit e47b1e5

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/core/observer/index.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ export function defineReactive (
189189
* already exist.
190190
*/
191191
export function set (target: Array<any> | Object, key: any, val: any): any {
192-
if (Array.isArray(target)) {
192+
if (Array.isArray(target) && typeof key === 'number') {
193193
target.length = Math.max(target.length, key)
194194
target.splice(key, 1, val)
195195
return val
@@ -198,7 +198,7 @@ export function set (target: Array<any> | Object, key: any, val: any): any {
198198
target[key] = val
199199
return val
200200
}
201-
const ob = target.__ob__
201+
const ob = (target : any).__ob__
202202
if (target._isVue || (ob && ob.vmCount)) {
203203
process.env.NODE_ENV !== 'production' && warn(
204204
'Avoid adding reactive properties to a Vue instance or its root $data ' +
@@ -219,11 +219,11 @@ export function set (target: Array<any> | Object, key: any, val: any): any {
219219
* Delete a property and trigger change if necessary.
220220
*/
221221
export function del (target: Array<any> | Object, key: any) {
222-
if (Array.isArray(target)) {
222+
if (Array.isArray(target) && typeof key === 'number') {
223223
target.splice(key, 1)
224224
return
225225
}
226-
const ob = target.__ob__
226+
const ob = (target : any).__ob__
227227
if (target._isVue || (ob && ob.vmCount)) {
228228
process.env.NODE_ENV !== 'production' && warn(
229229
'Avoid deleting properties on a Vue instance or its root $data ' +

test/unit/modules/observer/observer.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,17 @@ describe('Observer', () => {
284284
delProp(obj3, 'a')
285285
expect(hasOwn(obj3, 'a')).toBe(false)
286286
expect(dep3.notify.calls.count()).toBe(2)
287+
// set and delete non-numeric key on array
288+
const arr2 = ['a']
289+
const ob2 = observe(arr2)
290+
const dep2 = ob2.dep
291+
spyOn(dep2, 'notify')
292+
setProp(arr2, 'b', 2)
293+
expect(arr2.b).toBe(2)
294+
expect(dep2.notify.calls.count()).toBe(1)
295+
delProp(arr2, 'b')
296+
expect(hasOwn(arr2, 'b')).toBe(false)
297+
expect(dep2.notify.calls.count()).toBe(2)
287298
})
288299

289300
it('warning set/delete on a Vue instance', done => {

0 commit comments

Comments
 (0)