【问题标题】:Create an only numeric text field创建一个唯一的数字文本字段
【发布时间】:2018-08-14 10:53:59
【问题描述】:

我正在尝试使用 VueJS 构建一个唯一的数字字段。它有点工作,但出了点问题:

  1. PASS: 在文本字段中输入 12,VueJS 中的值为 12,视觉为 12。
  2. FAILS: 在文本字段中输入 12a,VueJS 中的值为 12,视觉为 12a。 (文本字段中的预期行为是 12)
  3. PASS: 在文本字段中输入 12a4,VueJS 中的值为 12a4,视觉为 124

你可以试试我做的这个 JSFiddle:https://jsfiddle.net/El_Matella/rr2qex8k/

这是我的文本字段组件:

const TextField = {
    template: '<div><input type="text" v-model="copy"></div>',
        props: ['value'],
        data () {
        return {
            copy: null
        }
    },
    created () {
        this.copy = this.value.toString()
    },
    watch: {
        value () {
            this.copy = this.value.toString()
        },
        copy () {
            this.$emit('input', this.copy)
        }
    }
}

下面的代码应该允许我将该文本字段组件用作唯一的数字文本:

new Vue({
    el: '#app',
    data: {
        number: 1
    },
    methods: {
        update (value) {
            this.number = parseInt(value.replace(/\D/g, ''))
        }
    },
    components: {
        TextField
    }
})

问题是当最后输入的字符是非数值时,输入字段没有更新。您必须输入其他数值才能更新输入并删除非数字字符。

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

在你的输入标签上试试这个

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>

<input type="number" />

你可以在这里检查兼容性:

https://caniuse.com/#search=type%3D%22number%22

【讨论】:

  • 这确实有效:jsfiddle.net/El_Matella/rr2qex8k/15charCode 在每个浏览器上都一样吗?
  • 是的,就是ASCII相关的,48到57是0到9个字符的编码,考虑到这个不能插入负图“-”
【解决方案2】:

您可以在计算值上使用 getter 和 setter 来清理输入值:

const TextField = {
    template: '<div><input type="text" v-model="inputValue"></div>',
    props: ['value'],
    data(){
        return {
            number: 0
        }
    },
    computed: {
        inputValue: {
            get: function(){
                return this.number;
            },
            set: function(value){
                this.number = parseInt(value.replace(/\D/g, ''))
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多