Skip to content

Commit

Permalink
fix(v-for): handle and warn when v-for receives non-integer range n…
Browse files Browse the repository at this point in the history
…umber (#2247)

close #2245
  • Loading branch information
underfin authored Oct 13, 2020
1 parent 8539c0b commit 02f355e
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/runtime-core/__tests__/helpers/renderList.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ describe('renderList', () => {
])
})

it('should warn when given a non-integer N', () => {
renderList(3.1, () => {})
expect(
`The v-for range expect an integer value but got 3.1.`
).toHaveBeenWarned()
})

it('should render properties in an object', () => {
expect(
renderList(
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime-core/src/helpers/renderList.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { VNodeChild } from '../vnode'
import { isArray, isString, isObject } from '@vue/shared'
import { warn } from '../warning'

/**
* v-for string
Expand Down Expand Up @@ -60,6 +61,10 @@ export function renderList(
ret[i] = renderItem(source[i], i)
}
} else if (typeof source === 'number') {
if (__DEV__ && !Number.isInteger(source)) {
warn(`The v-for range expect an integer value but got ${source}.`)
return []
}
ret = new Array(source)
for (let i = 0; i < source; i++) {
ret[i] = renderItem(i + 1, i)
Expand Down
7 changes: 7 additions & 0 deletions packages/server-renderer/__tests__/ssrRenderList.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ describe('ssr: renderList', () => {
expect(stack).toEqual(['node 0: 1', 'node 1: 2', 'node 2: 3'])
})

it('should warn when given a non-integer N', () => {
ssrRenderList(3.1, () => {})
expect(
`The v-for range expect an integer value but got 3.1.`
).toHaveBeenWarned()
})

it('should render properties in an object', () => {
ssrRenderList({ a: 1, b: 2, c: 3 }, (item, key, index) =>
stack.push(`node ${index}/${key}: ${item}`)
Expand Down
5 changes: 5 additions & 0 deletions packages/server-renderer/src/helpers/ssrRenderList.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isArray, isString, isObject } from '@vue/shared'
import { warn } from '@vue/runtime-core'

export function ssrRenderList(
source: unknown,
Expand All @@ -9,6 +10,10 @@ export function ssrRenderList(
renderItem(source[i], i)
}
} else if (typeof source === 'number') {
if (__DEV__ && !Number.isInteger(source)) {
warn(`The v-for range expect an integer value but got ${source}.`)
return
}
for (let i = 0; i < source; i++) {
renderItem(i + 1, i)
}
Expand Down

0 comments on commit 02f355e

Please sign in to comment.