Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using i18n in nuxt plugin

I am using nuxt with vuetify and I defined all my validations rules (for text inputs) in a single file like this:

// @/plugins/form_validations.js

export default Object.freeze({
  VALIDATIONS: {

    FIRSTNAME: [
      v => !!v || 'Firstname is required',
      v => (v && v.length >= 3) || 'Firstname must be at least 3 characters'
    ],

    // ...
})

I use them in my components like this:

import FormValidations from '@/plugins/form_validations.js'

export default {
  data() {
   firstnameRules: FormValidations.VALIDATIONS.FIRSTNAME
  }
}
<v-text-field
   v-model="firstname"
   :rules="firstnameRules"
/>

I want now to translate the text of this rules depending of the locale.

I have installed i18n following this example and can use it well in my components, for example like this:

<v-text-field
   ref="firstname"
   v-model="firstname"
   :label="$t('firstname')"
   :rules="firstnameRules"
    required />

However, I'm not able to use the translation plugin directly in my file where I grouped all the rules. I have seen that with nuxt you can access the context in plugins as follow:

export default ({ app, store }) => {
}

But I'm not able to define my constants using Object.freeze in that format.

I tried also this:


import i18n from '@/plugins/i18n.js'

export default Object.freeze({
  VALIDATIONS: {
    FIRSTNAME: [
      v => !!v || i18n.t('firstname_required'),
    ],
}

But I got an error that function t is not defined. How can I access the translation plugin in my rules?

like image 304
skuallpa Avatar asked Dec 08 '22 11:12

skuallpa


1 Answers

I was facing almost identical problem, here is my solution:

// @/plugins/validation-rules.js

export default ({app}) => {

  let i18n = app.i18n

  // You can use `this.$rules` anywhere in the Nuxt app.
  Vue.prototype.$rules = {
    required: [v => !!v || i18n.t('required')]
  }
}
<v-text-field
      v-model="email"
      :rules="this.$rules.required"
      label="E-mail"
      required
      ref="emailField"
></v-text-field>

When I change the language in my language switcher, the error message doesn't get shown in your switched language, you must re-type the erroneous email into the input field, but then the error message shows in correct language.

I'm also not sure about the Vue.prototype, it might be better to use combined inject.

like image 132
mtbno Avatar answered Dec 11 '22 07:12

mtbno