簡體   English   中英

如何向v模型添加約束

[英]How to add constraints to v-model

vuejs方面

如何正確添加約束(限制)到v-model 假設我只允許05之間的數字。

<input type="number" v-model="model"/>

也許我可以watch輸入值。 但這有點hacky,不是嗎?

UPD:其他選項是處理onChangeonKeyUp等事件以及其他事件: HTML文本輸入僅允許數字輸入

不要濫用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;
    } else if (value < 0 || Number.isNaN(value)) {
      this.model = 0;
    } else {
      this.model = value;
    }
  }
}

在這些情況下,我使用Vue Validator在這里示例JSFiddle:

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
      }
    },
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM