【发布时间】:2018-08-14 10:53:59
【问题描述】:
我正在尝试使用 VueJS 构建一个唯一的数字字段。它有点工作,但出了点问题:
- PASS: 在文本字段中输入 12,VueJS 中的值为 12,视觉为 12。
- FAILS: 在文本字段中输入 12a,VueJS 中的值为 12,视觉为 12a。 (文本字段中的预期行为是 12)
- 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
}
})
问题是当最后输入的字符是非数值时,输入字段没有更新。您必须输入其他数值才能更新输入并删除非数字字符。
【问题讨论】:
-
嗨,也许使用
type="number"并在 created 和 watch 中删除字符串转换this.copy = this.value.toString()会有所帮助吗? -
确实如此,但我不希望在输入末尾有小箭头:jsfiddle.net/El_Matella/rr2qex8k/7
标签: javascript vue.js