2016-07-25 69 views

回答

4

不要濫用watch這一點。使用綁定和事件的方法:

<input type="number" v-bind:value="model" @input="handleInput"/> 

JS:

methods: { 
    handleInput: function(event) { 
    var value = Number(event.target.value) 
    if (value > 5) { 
     this.model = 5 
    } 
    elseif (value < 0 || Number.isNaN(value)) { 
     this.model = 0 
    } 
    else 
     this.model = value 
    } 
    } 
} 
1

我使用Vue Validator對於這些情況下,樣品的jsfiddle here

HTML:

<div id="app"> 
    <pre>{{$testValidator | json}}</pre> 
    <validator name="testValidator"> 
    <form v-on:submit.prevent="submitForm" novalidate> 
     <input type="number" v-model="value" v-validate:value="{min:1, max:10}"/> 
     <span class="help-block" v-show="$testValidator.value.max || $testValidator.value.min">Please enter a number between 1 and 10.</span> 
     <br/> 
     <button type="submit">Submit</button> 
    </form> 
    </validator> 
</div> 

JS:

new Vue({ 
    el: "#app", 
    data: { 
    value: 1 
    }, 
    methods: { 
    submitForm: function() { 
     this.$validate(true); 
     if (this.$testValidator.valid) { 
     // do other stuff here 
     } 
    }, 
    } 
}); 
+0

你能否提供一些例子請 –

+0

我用一個例子編輯我的答案 – Gus