方法封裝
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>