需求是:
- 输入框只能输入数字,包括整数和小数
发现网上大部分文章的处理方式:
- 通过正则来处理输入,对其合法性进行判断校验,再将提示信息反馈给用户。体验欠佳
- 输入完成后进行解析,将字符串转换为数字。会导致显示的值和真实值不一致
比对一下几种方案后,最终使用的是 el-input type="number" 优化
实现
代码 App.vue
<template>
<div class="">
<h3>el-input</h3>
<el-input v-model="value1"></el-input>
<h3>el-input v-model.number</h3>
<el-input v-model.number="value2"></el-input>
<h3>el-input-number</h3>
<el-input-number v-model="value3"
:controls="false"></el-input-number>
<h3>el-input type="number"</h3>
<el-input v-model="value4"
type="number"></el-input>
<h3>el-input type="number" 优化</h3>
<el-input v-model="value5"
type="number"
class="mo-input--number"></el-input>
</div>
</template>
<script>
// created at 2022-06-02
export default {
name: 'App',
props: {},
components: {},
data() {
return {
value1: '',
value2: '',
value3: '',
value4: '',
value5: '',
};
},
computed: {},
methods: {
async getData() {},
},
created() {
this.getData();
},
};
</script>
<style lang="less">
.mo-input--number {
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type='number'] {
-moz-appearance: textfield;
}
}
</style>
<style lang="less" scoped>
</style>
依赖 package.json
{
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"devDependencies": {
"@vue/cli": "^5.0.4",
"@vue/cli-service": "^5.0.4",
"css-loader": "^6.7.1",
"less": "^4.1.2",
"less-loader": "^11.0.0",
"style-loader": "^3.3.1",
"vue-template-compiler": "^2.6.14"
},
"dependencies": {
"element-ui": "^2.15.8",
"vue": "2"
}
}
入口文件 main.js
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App.vue";
Vue.use(ElementUI);
new Vue({
el: "#app",
render: (h) => h(App),
});
几种方式对比
方式 | 效果 |
---|---|
el-input | 可以输入数字,和字符串 |
el-input v-model.number | 可以输入数字,和字符串 |
el-input-number | 可以输入数字,和字符串 |
el-input type=“number” | 仅能输入数字(整数和小数) |
总结
到此这篇关于element-ui中el-input只输入数字(包括整数和小数)的文章就介绍到这了,更多相关element-ui el-input输入数字内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!