在 nuxt.js 插件中调用 $t 函数
Call $t function in nuxt.js plugin
我正在构建一个 nuxt.js 应用程序。所以我的计划是将正在重用的辅助对象和函数注入到上下文中。
所以我创建了一个插件
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;
}
对象已正确注入上下文,我可以在需要的地方访问规则。
但是尝试 运行 函数 $t 使我出错
Cannot read property '_t' of undefined
所以基本上我想 运行 $t 函数并在事情发生时获取本地化消息。这可能吗?如果可以,怎么做?
所以我最终设法解决了它。
所以问题在于 this
在 JS
中的行为方式
我把代码改成了这样:
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;
}
然后从我的 component/page
data() {
const { firstNameRules } = this.$formValidators();
}
像那样做,this
一直保留到 $t
函数
尝试使用 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);
};
我正在构建一个 nuxt.js 应用程序。所以我的计划是将正在重用的辅助对象和函数注入到上下文中。
所以我创建了一个插件
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;
}
对象已正确注入上下文,我可以在需要的地方访问规则。 但是尝试 运行 函数 $t 使我出错
Cannot read property '_t' of undefined
所以基本上我想 运行 $t 函数并在事情发生时获取本地化消息。这可能吗?如果可以,怎么做?
所以我最终设法解决了它。
所以问题在于 this
在 JS
我把代码改成了这样:
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;
}
然后从我的 component/page
data() {
const { firstNameRules } = this.$formValidators();
}
像那样做,this
一直保留到 $t
函数
尝试使用 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);
};