This commit is contained in:
@jyuhsin
2025-09-05 18:01:54 +08:00
parent 91be38bb52
commit 267dcfa738
7 changed files with 194 additions and 132 deletions
@@ -0,0 +1,50 @@
// 劫持 validate:失败时先提示 + 滚动,再抛出异常(保持原有行为)
if (typeof Vue !== 'undefined') {
Vue.mixin({
mounted() {
this.$nextTick(() => {
const formRefs = Object.keys(this.$refs).filter(ref => {
const comp = this.$refs[ref];
return comp &&
comp.$options &&
comp.$options._componentTag === 'van-form';
});
formRefs.forEach(refName => {
const form = this.$refs[refName];
if (!form || form._validatedEnhanced) return;
const originalValidate = form.validate;
form.validate = function () {
// 保留原 validate 的返回值(Promise
const promise = originalValidate.call(this);
return promise.catch(errorInfo => {
if (errorInfo?.length > 0) {
const firstError = errorInfo[0];
if(firstError.message) {
Vue.prototype.$toast?.fail(firstError.message);
} else {
const fieldName = firstError.name;
// 滚动到字段
this.scrollToField(fieldName);
// 获取 label
const field = this.fields?.find(f => f.name === fieldName);
const label = field?.label;
// 提示用户
Vue.prototype.$toast?.fail(`${label} 必填`);
}
}
return new Promise(() => {});
});
};
form._validatedEnhanced = true;
});
});
}
});
}