Skip to content

Commit

Permalink
fix(custom-elements): cast numbers with Number rules
Browse files Browse the repository at this point in the history
Fix #4370
  • Loading branch information
posva committed Aug 19, 2021
1 parent 872b3f7 commit 8cea380
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
36 changes: 36 additions & 0 deletions packages/runtime-dom/__tests__/apiCustomElement.spec.ts
@@ -0,0 +1,36 @@
import { toNumber } from '../src/apiCustomElement'

describe('Custom Element', () => {
describe('toNumber', () => {
it('handles strings', () => {
expect(toNumber('')).toBe('')
expect(toNumber(null)).toBe('')
expect(toNumber('Something else')).toBe('Something else')
})

it('numbers', () => {
expect(toNumber('0')).toBe(0)
expect(toNumber('1')).toBe(1)
expect(toNumber('1.1')).toBe(1.1)
expect(toNumber('123e-1')).toBe(12.3)
expect(toNumber('Infinity')).toBe(Infinity)
})

it('NaN', () => {
expect(toNumber('NaN')).toBeNaN()
expect(toNumber('nan')).not.toBeNaN()
})

// all of these are handled by Number
it('string non decimal bases', () => {
expect(toNumber('0b0')).toBe(0)
expect(toNumber('0b1')).toBe(1)

expect(toNumber('0o3')).toBe(3)
expect(toNumber('0o0')).toBe(0)

expect(toNumber('0x0')).toBe(0)
expect(toNumber('0xf')).toBe(15)
})
})
})
9 changes: 8 additions & 1 deletion packages/runtime-dom/src/apiCustomElement.ts
Expand Up @@ -21,7 +21,7 @@ import {
ConcreteComponent,
ComponentOptions
} from '@vue/runtime-core'
import { camelize, extend, hyphenate, isArray, toNumber } from '@vue/shared'
import { camelize, extend, hyphenate, isArray } from '@vue/shared'
import { hydrate, render } from '.'

export type VueElementConstructor<P = {}> = {
Expand Down Expand Up @@ -342,3 +342,10 @@ export class VueElement extends BaseClass {
}
}
}

export function toNumber(value: string | null): number | string {
// for Number('') and Number(null) as they both become 0
if (!value) return ''
const casted = Number(value)
return value === 'NaN' || !Number.isNaN(casted) ? casted : value
}

0 comments on commit 8cea380

Please sign in to comment.