需求是:
- 输入框只能输入数字,包括整数和小数
发现网上大部分文章的处理方式:
需求是:
- 输入框只能输入数字,包括整数和小数
发现网上大部分文章的处理方式:
- 通过正则来处理输入,对其合法性进行判断校验,再将提示信息反馈给用户。体验欠佳
- 输入完成后进行解析,将字符串转换为数字。会导致显示的值和真实值不一致
比对一下几种方案后,最终使用的是 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), });