方法封装
limit.js
export default {
/**
* 限制只能输入数字,且保留小数后两位
* @param {string} value - 输入的值
* @param {string} name - 匹配的对象属性 [mkPrice | slPrice]
*/
limitInput(value) {
return ("" + value)
.replace(/[^\d^\.]+/g, "")
.replace(/^0+(\d)/, "$1")
.replace(/^\./, "0.")
.match(/^\d*(\.?\d{0,2})/g)[0] || "";
},
/**
* 限制输入大于等于0小于等于1两位小数
* @param {string} value - 输入的值
* @param {string} name - 匹配的对象属性 [mkPrice | slPrice]
*/
limitDiscount(value) {
return ("" + value)
.replace(/[^\d^\.]+/g, "")
.replace(/^0+(\d)/, "0")
.replace(/^[1-9]/, "0")
.replace(/^\./, "0.")
.match(/^\d*(\.?\d{0,2})/g)[0] || "";
},
}
main.js
// 将限制函数文件绑定到vue原型上,供全局使用
import limit from "./api/limit.js";
Vue.prototype.$limit = limit;
组件使用
<el-input v-model="form.price" placeholder="请输入单价" @input="(e) => (form.price= $limit.limitInput(e))"></el-input>