Search code examples
vue.jsvuejs3vue-composition-apivue-i18n

i18n translate form rules on language change problem


I`m using vue-i18n set as options api from main.js. All set and working. In my form which is one of router views all labels are translated with $t('message.helper').

What I want is rules warnings translated also. For that I used i18n via composition api with useI18n from form component itself. Now rules look like

const rules = reactive<FormRules>({
      name: [
        { required: true, message: t('message.name_helper'), trigger: "blur" },
        { min: 3, message: t('message.name_helper2'), trigger: "blur" },
      ]})

form now shows warning but only default ones. If I change language, form languages are changed, warnings still in default language.

My main.js looks like so

import { createI18n } from 'vue-i18n'
const app = createApp(App)
const i18n = createI18n({
    locale: 'ee', // set locale
  fallbackLocale: 'ee', // set fallback locale
  messages
  })

app.use(i18n);
app.mount('#app');

My main form looks like

import { useI18n } from 'vue-i18n';
export default {
  setup() {
const {t}  = useI18n();

return {}
t
}
}

My guess is to watch for locale change with

watch(()=>store.getters.currentLang,(newVal) => { //watch the getter
 
      i18n.locale.value = store.getters.currentLang;
      locale = i18n.locale.value;
    },{
      immediate:true
    });

But still cant make it working, getters are nott defined somehow.


Solution

  • You could define rules as computed property to track changes effectively :

    const rules = computed<FormRules>(()=>({
          name: [
            { required: true, message: t('message.name_helper'), trigger: "blur" },
            { min: 3, message: t('message.name_helper2'), trigger: "blur" },
          ]}))