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?
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