如何防止Vue输入设置值?

时间:2018-09-10 23:17:14

标签: vuejs2

我有以下Vue代码:

// HTML
<div id="app">
  Value: <pre>{{ value }}</pre>
  <input type="text" :value="value" @input="setValue">
</div>

// JS
new Vue({
  el: "#app",
  data: {
    value: '',
  },
  methods: {
    setValue(event){
      /* Remove non-numeric values */
        this.value = event.target.value.replace(/[^\d]/g, '');
    }
  }
});

我将其设置在JSFiddle上的位置:http://jsfiddle.net/eywraw8t/353729/

为什么输入法允许我输入非数字值?

如果运行上面的代码,然后在输入元素中输入非数字乱码(例如asdasfa),则会看到输入元素将包含您输入的文本(asdasfa),但输入上方的元素将为空!

我想限制用户只允许在输入中输入数字。我想仅使用Vue,不使用第三方库或type="number"来做到这一点。

2 个答案:

答案 0 :(得分:2)

因为this.value不变(总是=''),所以不会触发重新渲染。

解决方案

您可以使用this.$forceUpdate()强制重新渲染。

或使用具有不同值的绑定键。

new Vue({
  el: "#app",
  data: {
    value: '',
    errorDescription: ''
  },
  methods: {
  	setValue(event){
      /* Remove non-numeric values */
    	this.value = event.target.value.replace(/[^\d]/g, '')
      this.errorDescription = 'Only Number allow'
      this.$forceUpdate()
    }
  }
})
.error {
  background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  Value: <pre>{{ value }}</pre><span class="error">{{errorDescription}}</span>
  <input type="text" :value="value" @input="setValue">
</div>

答案 1 :(得分:1)

问题在于Vue不会看到value数据属性的更改,因为当您滤除非数字时,实际上是在向其分配相同的字符串值。由于字符串在内容相同时是不变的且相同,因此不会触发Vue的反应性。

一个简单的解决方案是将<input>值手动设置为仅数字的新值。

this.value = event.target.value = event.target.value.replace(/\D/g, '')

http://jsfiddle.net/9o2tu3b0/

相关问题