fix v-model number conversion (fix #3140)

This commit is contained in:
Evan You 2016-06-22 21:43:52 -04:00
parent dcd82c2429
commit 3fe127b05a
5 changed files with 19 additions and 3 deletions

View File

@ -94,6 +94,8 @@ declare interface Component {
) => Object | void;
// toString
_s: (value: any) => string;
// toNumber
_n: (value: string) => number | string;
// resolveFilter
_f: (id: string) => Function;
// renderList

View File

@ -5,7 +5,7 @@ import VNode, { emptyVNode } from '../vdom/vnode'
import { normalizeChildren } from '../vdom/helpers'
import {
warn, bind, isObject, toObject,
nextTick, resolveAsset, renderString
nextTick, resolveAsset, renderString, toNumber
} from '../util/index'
import {
@ -96,6 +96,8 @@ export function renderMixin (Vue: Class<Component>) {
// toString for mustaches
Vue.prototype._s = renderString
// number conversion
Vue.prototype._n = toNumber
// filter resolution helper
const identity = _ => _

View File

@ -101,7 +101,7 @@ function genDefaultModel (
const valueExpression = `$event.target.value${trim ? '.trim()' : ''}`
let code = number || type === 'number'
? `${value}=Number(${valueExpression})`
? `${value}=_n(${valueExpression})`
: `${value}=${valueExpression}`
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`

View File

@ -11,6 +11,15 @@ export function renderString (val: any): string {
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
export function toNumber (val: string): number | string {
const n = parseFloat(val, 10)
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.

View File

@ -45,7 +45,10 @@ describe('Directive v-model text', () => {
expect(vm.test).toBe(1)
vm.$el.value = '2'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe(2)
// should let strings pass through
vm.$el.value = 'f'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('f')
})
it('.trim modifier', () => {