项目需要国际化处理,发现一个问题:当切换语言时表单验证的提示信息没有同时更新过来
看了一些解决方案,可以把rules放到computed里,但是这样切换语言会导致整个表单重新验证,而我只想把已经提示错误信息的几个表单项改变提示语言,
解决方案:
不使用message传入错误提示 ,手动传入验证规则
<Form ref="formUser" :model="formData" :rules="ruleValidate">
<FormItem prop="userName">
<Input v-model="formData.userName" type="text" name="userName"
:placeholder="$t('login.userNamePlaceholder')">
<Icon type="ios-person-outline" slot="prepend" size="21"></Icon>
</Input>
</FormItem>
<FormItem prop="passWord">
<Input v-model="formData.passWord" type="password" name="password" @keyup.enter="login"
:placeholder="$t('login.passwordPlaceholder')">
<Icon type="ios-lock-outline" slot="prepend" size="21"></Icon>
</Input>
</FormItem>
<FormItem class="login-btn-wrap">
<Button type="primary" long @click="login('formUser')">{{$t('login.loginBtn')}}</Button>
</FormItem>
</Form>
ruleValidate: {
userName: [
{
required: true,
trigger: 'blur',
validator: (rule, value, callback) => {
if (!value) {
return callback(new Error(this.$t("login.userNameValidate")));
} else {
callback();
}
}
}
],
passWord: [
{
required: true,
trigger: 'blur',
validator: (rule, value, callback) => {
if (!value) {
return callback(new Error(this.$t('login.passWordValidateNull')));
} else if (!/^\w{6,20}$/.test(value)) {
return callback(new Error(this.$t('login.passWordValidateDigits')));
} else {
callback();
}
}
}
]
}
监听i18n,切换语言时查找已经提示错误的表动项,手动触发验证
watch: {
"$i18n.locale" (){
this.$refs['formUser'].fields.forEach(item => {
if (item.validateState === 'error') {
this.$refs['formUser'].validateField(item.prop)
}
})
}
},
参考文献:https://blog.csdn.net/weixin_43846401/article/details/102747816