// plugins/limit-plugin.js const LimitDirective = { install(Vue) { Vue.directive('limit', { bind(el, binding, vnode) { const input = el.querySelector('input') if (!input) return const { min, max } = binding.value || {} const handleInput = (e) => { const value = e.target.value if (value === '') return const numValue = parseFloat(value) if (isNaN(numValue)) return let corrected = false let newValue = numValue // 检查最小值 if (min !== undefined && numValue < min) { newValue = min corrected = true } // 检查最大值 if (max !== undefined && numValue > max) { newValue = max corrected = true } if (corrected) { e.target.value = newValue // 触发v-model更新 vnode.componentInstance.$emit('input', newValue) } } el._limitHandler = handleInput input.addEventListener('input', handleInput) }, unbind(el) { const input = el.querySelector('input') if (input && el._limitHandler) { input.removeEventListener('input', el._limitHandler) delete el._limitHandler } } }) } } export default LimitDirective // main.js 中使用 // import LimitDirective from './plugins/limit-plugin' // Vue.use(LimitDirective)