1.新建js文件
// 验证规则
const regStr = /^(0{1}|[1-9]{1,})([.][0-9]{0,2})?$/
let inputVal = ''
const modifyInputVal = {
created(el, binding, vnode, prevVnode) {
},
beforeUpdate(el, binding) {
if (regStr.test(binding.value.val) || binding.value.val === "") {
inputVal = binding.value.val
}
},
updated(el, binding) {
if (!regStr.test(binding.value.val) && binding.value.val !== "") {
binding.value.set(inputVal)
} else {
binding.value.set(binding.value.val)
}
}
}
export default {
modifyInputVal
}
2.在main.js中全局引入
import { createApp } from 'vue'
import App from './App.vue'
import myDirective from './utils/myDirective' // 自定义指令
const app = createApp(App)
// 全局引入自定义指令
Object.keys(myDirective).forEach(item => {
app.directive(item, myDirective[item])
})
app.mount('#app')
3.在vue文件中使用
<n-input placeholder="账号" v-modify-input-val="{set:((account)=>{formValue.account = account}),val:formValue.account}" maxlength="11" v-model:value="formValue.account"></n-input>