2016-07-25 45 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