Article directory
Unexpectedly! I, Cao, have been wandering around for dozens of years, but I was tested and said that my input had bugs. . .
hint
- In fact, in almost all browsers, the value you get
input[type=number]
at the end is alsostring
of type;
I think the reason is: if the transmitted number is too large, there may be a problem of loss of precision (16 bits), and the front and rear ends cannot carry out correct data. Interaction, so usingstring
is the correct solution. - If you just want to use it
number
, it's not too expensive. (I don't care if the data is correct or not, I just want to use it, just for fun!)
Just convert the value to the type at the timeblur
ofnumber
;
why not convert it at the timeinput
of ? Because you will never be able to enter the point.
float
type , if you don’t believe me, you can try
Native onInput
implementation
html
<input type="text" id="input" oninput="inputHandle()">
javascript
var inputNode = document.getElementById("input");
function inputHandle() {
var value = inputNode.value;
// 匹配规则: ± 号开头,匹配任意数字和 . (问题匹配到多个.)
value = value.match(/^[-+]{1}|[\d.]/g) || [];
value = ''.concat(...value);
// 消除 {2, n} 个点 '.'
const valueSplitArr = value.split('.');
value = '';
valueSplitArr.forEach((item, index) => {
value = (index === 1) ? value.concat(`.${
item}`) : value.concat(item);
});
inputNode.value = value;
}
vue command implementation
If you use the vue command, it must be registered globally
File Directory
inputNumberLimit.js directive implementation
/**
* DOM(输入框) 输入数据时,规范 input内容 ()
* @param {Object} vNode Vue 编译生成的虚拟节点(当前绑定节点)
* @param {DOM} el 指令所绑定的元素,可以用来直接操作 DOM。
*/
function inputHandle(vNode, el) {
const dom = el;
const vn = vNode;
let value = dom.value.toString().match(/^[-+]{1}|[\d.]/g) || []; // 匹配规则: ± 号开头,匹配任意数字和 . (问题匹配到多个.)
value = ''.concat(...value);
// 消除 {2, n} 个点 '.'
const valueSplitArr = value.split('.');
value = '';
valueSplitArr.forEach((item, index) => {
value = (index === 1) ? value.concat(`.${
item}`) : value.concat(item);
});
vn.context.value = value;
dom.value = value;
}
const inputNumberLimit = {
update(el, binding, vNode) {
inputHandle(vNode, el);
},
};
export default inputNumberLimit;
Instruction index.js summary
import inputNumberLimit from './modules/inputNumberLimit';
const directives = {
inputNumberLimit,
// 新加的指令在这儿引入
};
export default {
// Vue.use() 其实就是调用 install(Vue) 方法
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
};
Use it in main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import myDirection from './directive/index';
Vue.config.productionTip = false;
Vue.use(myDirection);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
Use the page directly
<!-- 同时用v-model绑定一下数据 --->
<input type="text" v-inputNumberLimit v-model="value">
{
{value}}