0

I am building a nuxt.js application. So my plan is to inject helper object and functions that are being reused to context.

So I created a plugin

export default (context) => {
     const { $t } = context.app;

     const validators = {
      firstNameRules: [
         v => !!v || $t('formValidation.NO_FIRST_NAME'),
         v => v.length < 128 || $t('formValidation.INVALID_FIRST_NAME_TOO_LONG')
       ]
     };

     context.$formValidators = validators;
}

The object is injected to context correctly and I can access rules where I want. However trying to run the function $t brings me to error

Cannot read property '_t' of undefined 

So basically I would like to run $t function and to get localized message when stuff happens. Is that possible and if yes, how?

errror compiling message

Rouz
  • 1,247
  • 2
  • 15
  • 37

2 Answers2

1

So I managed to solve it eventually.

So the thing is in the way this behaves in JS

I changed the code to be like this:

export default function(context) {
  function getValidators() {
    return {
      firstNameRules: [
        v => !!v || this.$t('formValidation.NO_FIRST_NAME'),
        v => v.length < 128 || this.$t('formValidation.INVALID_FIRST_NAME_TOO_LONG')
      ]
    };
  }

  Vue.prototype.$formValidators = getValidators;
  context.$formValidators = getValidators;
}

And then from my component/page

data() {
  const { firstNameRules } = this.$formValidators();
}

Doing things like that, this is preserved all the way down to the $t function

Rouz
  • 1,247
  • 2
  • 15
  • 37
0

Try to use an inject:

export default (context, inject) => {
  const { $t } = context.app;
  const validators = {
    firstNameRules: [
      v => !!v || $t('formValidation.NO_FIRST_NAME'),
      v => v.length < 128 || $t('formValidation.INVALID_FIRST_NAME_TOO_LONG')
    ]
  };

  context.$formValidators = validators;
  inject('formValidators', validators);
};
gleam
  • 861
  • 6
  • 12
  • Nope, this does not change anything. But I did manage to solve things. `this` behavior was problematic – Rouz Feb 05 '19 at 18:04