How can I disable all dot on input type number ? vue.js 2

别来无恙 提交于 2019-12-11 01:57:11

问题


My html code like this :

<div id="app">
  <input type="number" v-model="quantity"/>
</div>

My vue component like this :

new Vue({
  el: '#app',
  data: {
    quantity: ''
  },
  watch: {
    quantity (val) {
      this.quantity = val.replace('.', '')
    }
  }
})

Demo and full code like this : https://jsfiddle.net/50wL7mdz/67375/

For example

I input 10.2, it will automatic to be 102

If I input 10..2, it not automatic to be 102

So if multiple dot, it does not work

How can I solve this problem?


回答1:


Because you are using type="number", the browser is doing some internal processing, so the value of the input (which is bound to your variable) is a Number, and is not exactly the same as the text in the box.

In particular, if the text in the box is not a valid number, the internal value is empty. When you type one '.', the value doesn't change: 10. and 10 are the same numeric value. When you type the 2nd '.', the value becomes invalid, so the internal value is empty. Somewhat confusingly, what you typed in the input stays visible, but there is no way to get at it.

Your options are to stop using type="number" in which case your code will work as written (but you don't have the up- and down-arrow functionality for changing the value), or to do something tricky.

Update: The solution below works relatively nicely by forcing a canonicalized version of the number to be used. The caveat is that your cursor will be moved to the end of the number each time you make a change. You can address that, but it's somewhat complicated so I didn't do it here.

new Vue({
  el: '#app',
  data: {
    quantity: ''
  },
  computed: {
    ppQuantity: {
      get() {
        return this.quantity;
      },
      set(val) {
        this.quantity = '';
        this.$nextTick(() => {
          this.quantity = val.replace('.', '');
        });
      }
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <input type="number" v-model="ppQuantity">
</div>


来源:https://stackoverflow.com/questions/46650472/how-can-i-disable-all-dot-on-input-type-number-vue-js-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!