element el-input 只能輸入數字,限制最大最小,小數位數 --使用 directive
1. 創建onlyNumber指令
src/directive/el-input/onlyNumber.js
export default { inserted(el, vDir, vNode) { // vDir.value 有指令的參數 let content // 按鍵按下=>只允許輸入 數字/小數點 el.addEventListener('keypress', (event) => { const e = event || window.event const inputKey = String.fromCharCode(typeof e.charCode === 'number' ? e.charCode : e.keyCode) const re = /\d|\./ content = e.target.value // 定義方法,阻止輸入 function preventInput() { if (e.preventDefault) { e.preventDefault() } else { e.returnValue = false } } if (!re.test(inputKey) && !e.ctrlKey) { preventInput() } else if (content.indexOf('.') > 0 && inputKey === '.') { // 已有小數點,再次輸入小數點 preventInput() } }) // 按鍵彈起=>並限制最大最小 el.addEventListener('keyup', (event) => { const e = event || window.event content = parseFloat(e.target.value) if (!content) { content = 0.0 } let arg_max = '' let arg_min = '' if (vDir.value) { arg_max = parseFloat(vDir.value.max) arg_min = parseFloat(vDir.value.min) } if (arg_max && content > arg_max) { e.target.value = arg_max content = arg_max e.target.dispatchEvent(new Event('input')) } if (arg_min && content < arg_min) { e.target.value = arg_min content = arg_min e.target.dispatchEvent(new Event('input')) } }) // 失去焦點=>保留指定位小數 el.addEventListener('focusout', (event) => { // 此處會在 el-input 的 @change 后執行 const e = event || window.event content = parseFloat(e.target.value) if (!content) { content = 0.0 } let arg_precision = 0 // 默認保留至整數 if (vDir.value.precision) { arg_precision = parseFloat(vDir.value.precision) } e.target.value = content.toFixed(arg_precision) e.target.dispatchEvent(new Event('input')) // -- callback寫法1 // vNode.data.model.callback = ()=>{ // e.target.value = content.toFixed(arg_precision) // } // vNode.data.model.callback(); // -- callback 寫法2 // vNode.data.model.callback( // e.target.value = content.toFixed(arg_precision) // ) }) } }
2. onlyNumber指令導出 src/directive/el-input/index.js
import onlyNumber from './onlyNumber'
const install = (Vue) => {
Vue.directive('onlyNumber', onlyNumber)
}
/*
Vue.use( plugin )
安裝 Vue.js 插件。如果插件是一個對象,必須提供 install 方法。
如果插件是一個函數,它會被作為 install 方法。install 方法調用時,會將 Vue 作為參數傳入。
該方法需要在調用 new Vue() 之前被調用。
當 install 方法被同一個插件多次調用,插件將只會被安裝一次。
*/
if (window.Vue) {
window['onlyNumber'] = onlyNumber
Vue.use(install); // eslint-disable-line
}
onlyNumber.install = install
export default onlyNumber
3.全局調用 src/main.js
import onlyNumber from '@/directive/el-input'
Vue.use(onlyNumber)
4.應用於頁面
<el-input v-model="amount" v-onlyNumber="{precision:2,min:0,max:9999}" type="number" placeholder="請輸入金額" size="mini" ></el-input>