onlyNumber.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export default {
  2. inserted(el, vDir, vNode) {
  3. // vDir.value 有指令的参数
  4. let content
  5. // 按键按下=>只允许输入 数字/小数点
  6. el.addEventListener('keypress', (event) => {
  7. const e = event || window.event
  8. const inputKey = String.fromCharCode(typeof e.charCode === 'number' ? e.charCode : e.keyCode)
  9. const re = /\d|\./
  10. content = e.target.value
  11. // 定义方法,阻止输入
  12. function preventInput() {
  13. if (e.preventDefault) {
  14. e.preventDefault()
  15. } else {
  16. e.returnValue = false
  17. }
  18. }
  19. if (!re.test(inputKey) && !e.ctrlKey) {
  20. preventInput()
  21. } else if (content.indexOf('.') > 0 && inputKey === '.') {
  22. // 已有小数点,再次输入小数点
  23. preventInput()
  24. }
  25. })
  26. // 按键弹起=>并限制最大最小
  27. el.addEventListener('keyup', (event) => {
  28. const e = event || window.event
  29. content = parseFloat(e.target.value)
  30. if (!content) {
  31. content = 0.0
  32. }
  33. let arg_max = ''
  34. let arg_min = ''
  35. if (vDir.value) {
  36. arg_max = parseFloat(vDir.value.max)
  37. arg_min = parseFloat(vDir.value.min)
  38. }
  39. if (arg_max && content > arg_max) {
  40. e.target.value = arg_max
  41. content = arg_max
  42. e.target.dispatchEvent(new Event('input'))
  43. }
  44. if (arg_min && content < arg_min) {
  45. e.target.value = arg_min
  46. content = arg_min
  47. e.target.dispatchEvent(new Event('input'))
  48. }
  49. })
  50. // 失去焦点=>保留指定位小数
  51. el.addEventListener('focusout', (event) => {
  52. // 此处会在 el-input 的 @change 后执行
  53. const e = event || window.event
  54. content = parseFloat(e.target.value)
  55. if (!content) {
  56. content = 0.0
  57. }
  58. let arg_precision = 0 // 默认保留至整数
  59. if (vDir.value.precision) {
  60. arg_precision = parseFloat(vDir.value.precision)
  61. }
  62. e.target.value = content.toFixed(arg_precision)
  63. e.target.dispatchEvent(new Event('input'))
  64. // -- callback写法1
  65. // vNode.data.model.callback = ()=>{
  66. // e.target.value = content.toFixed(arg_precision)
  67. // }
  68. // vNode.data.model.callback();
  69. // -- callback 写法2
  70. // vNode.data.model.callback(
  71. // e.target.value = content.toFixed(arg_precision)
  72. // )
  73. })
  74. }
  75. }