commit
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
if (typeof Vue === 'undefined') {
|
||||
console.error('Vue is not defined. Please include Vue first.')
|
||||
}
|
||||
|
||||
const MARK = '__autoEnhance_validated__'
|
||||
|
||||
function autoEnhanceForm(formVm) {
|
||||
// 防止重复处理
|
||||
if (formVm[MARK]) return
|
||||
formVm[MARK] = true
|
||||
|
||||
const vnode = formVm.$vnode
|
||||
if (vnode && vnode.data && vnode.data.attrs && vnode.data.attrs['no-auto-enhance'] !== undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
const originalValidate = formVm.validate
|
||||
|
||||
formVm.validate = function(callback) {
|
||||
originalValidate(async (valid, fields) => {
|
||||
if (valid) {
|
||||
callback?.(valid, fields)
|
||||
} else {
|
||||
const firstField = Object.keys(fields)[0]
|
||||
const fieldErrors = fields[firstField]
|
||||
const errorMessage = fieldErrors[0].message
|
||||
|
||||
let finalMessage = errorMessage
|
||||
|
||||
const formItem = formVm.fields?.find(item => item.prop === firstField)
|
||||
|
||||
if (errorMessage === '必填' && formItem && formItem.label) {
|
||||
finalMessage = `${formItem.label} 必填`
|
||||
}
|
||||
|
||||
// 提示
|
||||
if (formVm.$message) {
|
||||
formVm.$message({
|
||||
message: finalMessage,
|
||||
type: 'error',
|
||||
})
|
||||
} else {
|
||||
alert(finalMessage)
|
||||
}
|
||||
|
||||
await formVm.$nextTick()
|
||||
|
||||
if (formItem && formItem.$el) {
|
||||
const inputEl =
|
||||
formItem.$el.querySelector('input') ||
|
||||
formItem.$el.querySelector('textarea') ||
|
||||
formItem.$el.querySelector('.el-input__inner') ||
|
||||
formItem.$el.querySelector('.el-textarea__inner')
|
||||
if (inputEl) {
|
||||
inputEl.focus()
|
||||
}
|
||||
}
|
||||
callback?.(valid, fields)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 拦截 Vue.component
|
||||
if (Vue.component) {
|
||||
const originalComponent = Vue.component
|
||||
Vue.component = function(name, def) {
|
||||
const res = originalComponent.apply(this, arguments)
|
||||
|
||||
if (name === 'el-form' && def) {
|
||||
const originalMounted = def.mounted
|
||||
def.mounted = function() {
|
||||
autoEnhanceForm(this)
|
||||
originalMounted?.call(this)
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
if (Vue.extend) {
|
||||
const originalExtend = Vue.extend
|
||||
Vue.extend = function() {
|
||||
const Ctor = originalExtend.apply(this, arguments)
|
||||
|
||||
if (Ctor.options?.name === 'ElForm') {
|
||||
const originalMounted = Ctor.options.mounted
|
||||
Ctor.options.mounted = function() {
|
||||
autoEnhanceForm(this)
|
||||
originalMounted?.call(this)
|
||||
}
|
||||
}
|
||||
|
||||
return Ctor
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user