(vue 2.x )Antdv formModel组件错误提示无法随i18n切换自动切换的解决办法

226 阅读1分钟

方法就是使用watch监听语言变化,判断当前form的fields中校验为error的,并重新触发它们的校验

示例代码如下,上班摸鱼纯手打,可能会有错误

Example.vue

<template>
// 这个ref watch里会用到
<a-form-model ref="ruleForm" :model="ruleForm" :rules="rules">
    <a-form-model-item :label="$t('xx.name')" prop="name">
        <a-input v-model="ruleForm.name" />
    </a-form-model-item>
</a-form-model>
<template>
<script>
export default {
    data(){
        return {
            ruleForm: {
                name: undefined
            },
            rules: {
                name: [{
                    validator: this.validateName,
                    trigger: 'blur'
                }]
            }
        }
        
    },
    methods: {
        validateName(rule, value, callback) {
            if(!value) {
                // 错误提示
                callback(new Error(this.$t('xx.xx')))
            } else {
                callback()
            }
        }
    },
    // 关键代码
    watch: {
        '$i18n.locale' () {
            for(const item of this.$refs.ruleForm.fields) {
                if(item.validateState === 'error') {
                    this.$refs.ruleForm.validateField(item.prop)
                }
            }
        }
    }
    
}
</script>

此外,我们可以把watch提取出来放到mixins里面,并在data里提供一个ref配置项降低耦合

export default {
    data () {
        return {
            bindRuleForms: ['ruleForm']
        }
    },
    watch: {
        '$i18n.locale' () {
            if (this.bindRuleForms?.length) {
                for (const name of this.bindRuleForms) {
                    for (const item of this.$refs[name].fields) {
                        if (item.validateState === 'error') {
                            this.$refs[name].validateField(item.prop)
                        }
                    }
                }
            }
        }
    }
}