繁体   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