Vue、Yup 和 i18n 的翻译问题

问题描述 投票:0回答:5

我有一个 Vue.js 应用程序(带有 Vite),其中我使用 Vee-validate 和 Yup 进行表单验证,并使用 i18n 进行消息翻译。但是,当用户设置时,模式中的自定义错误不会实时更新

$i18n.locale='xx'

架构:

import { useI18n } from "vue-i18n"

const {t} = useI18n()

const schema = yup.object().shape({
  username: yup
    .string()
    .required(t("field_required"))
    .email(t("field_error_email")),
  password: yup.string().required(t("field_required"))
})

使用

$t("message")
直接打印到模板的消息可以正常工作。

版本:

"dependencies": {
    "vee-validate": "^4.5.11",
    "vue": "^3.2.33",
    "vue-i18n": "^9.1.9",
    "yup": "^0.32.11"
}
javascript vue.js yup vite vue-i18n
5个回答
2
投票

t("field_required")
在组件设置期间作为字符串传递,它不能是反应性的。为了具有反应性,应该在真正需要访问消息时(即在模式验证期间)对其进行评估。预计
required
等模式方法会接受一个函数来延迟评估消息以达到此目的,而且它们确实这样做了。

应该是:

const schema = yup.object().shape({
  username: yup
    .string()
    .required(() => t("field_required"))
    ...

0
投票

在观察者内部,它看起来像这样:

   watch(i18n.global.locale, () => {
     if (<TOBEVALIDATED>.meta.value.touched) <TOBEVALIDATED>.validate();
   });

metavalidate 都是可以从 useForm() 中解构的值,如果您使用例如vee 验证。


0
投票

您可以像这样传递翻译后的字符串:

import * as yup from 'yup';

const schema = yup.object({
    name: yup.string().required(),
    email: yup.string('Must be string')
                .email('Must be email')
                .required('Required input'),
    password: yup.string().required().min(6),
});

enter image description here

另请检查此链接:https://www.npmjs.com/package/yup#validation-tests


0
投票

我找到了一种方法,但我收到一条带有“”的消息。 例如,我们应该得到(密码字段是必需的),但是我们得到了(“密码字段是必需的”)。

这是我的代码。

import UseForm from '@/composable/validation/schemas/UseForm';
import { useI18n } from 'vue-i18n';

const mRequired = (fieldName: string) => {
  const { t } = useI18n();
  return computed<string>(() => {
    return t('validation.required', { field: t(`fields.${fieldName}`) });
  });
};

const { errors, values, handleSubmit, resetForm } = UseForm(
  yup.object({
    password: yup.string().required(mRequired('password')),
  }),
);

在此输入图片描述


0
投票

为什么不全局设置它,例如在 setLocale() 中?

© www.soinside.com 2019 - 2024. All rights reserved.