limit-plugin.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // plugins/limit-plugin.js
  2. const LimitDirective = {
  3. install(Vue) {
  4. Vue.directive('limit', {
  5. bind(el, binding, vnode) {
  6. const input = el.querySelector('input')
  7. if (!input) return
  8. const { min, max } = binding.value || {}
  9. const handleInput = (e) => {
  10. const value = e.target.value
  11. if (value === '') return
  12. const numValue = parseFloat(value)
  13. if (isNaN(numValue)) return
  14. let corrected = false
  15. let newValue = numValue
  16. // 检查最小值
  17. if (min !== undefined && numValue < min) {
  18. newValue = min
  19. corrected = true
  20. }
  21. // 检查最大值
  22. if (max !== undefined && numValue > max) {
  23. newValue = max
  24. corrected = true
  25. }
  26. if (corrected) {
  27. e.target.value = newValue
  28. // 触发v-model更新
  29. vnode.componentInstance.$emit('input', newValue)
  30. }
  31. }
  32. el._limitHandler = handleInput
  33. input.addEventListener('input', handleInput)
  34. },
  35. unbind(el) {
  36. const input = el.querySelector('input')
  37. if (input && el._limitHandler) {
  38. input.removeEventListener('input', el._limitHandler)
  39. delete el._limitHandler
  40. }
  41. }
  42. })
  43. }
  44. }
  45. export default LimitDirective
  46. // main.js 中使用
  47. // import LimitDirective from './plugins/limit-plugin'
  48. // Vue.use(LimitDirective)