使原型在 vuex 中可访问
Make prototype accessible in vuex
在我的 app.js
文件中,我构建了这个以便我可以在 vue 中使用翻译:
Vue.prototype.trans = string => _.get(window.i18n, string);
这在我的 vue 文件中运行良好:
{{ trans('translation.name') }}
问题是我正在使用 vuex
,我需要翻译模块中的一些内容:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default {
namespaced: true,
state: {
page: 1,
criterias: [
{
name: this.trans('translation.name'),
filter: "life",
active: false
}
}
}
但是这里this.trans('translation.name')
是行不通的。我怎样才能让它发挥作用?
我可以建议您解决方法。您可以使用突变将 criterias
的初始化从 store.js
移动到您的 App.vue
。
store.js
state: {
page: 1,
criterias: []
},
mutations: {
setCriterias(state, payload) {
state.criterias = payload;
},
}
App.vue
beforeMount() {
this.$store.commit( 'setCriterias' , [
{
name: this.trans('translation.name'),
filter: "life",
active: false
}
])
}
由于您的翻译内容 window.i18n
无论如何都是全球性的,为什么不定义另一个 trans
类似于您在商店模块中添加到 Vue.prototype
的方法?
如果您担心以后必须在两个地方编辑此方法,请使用这个方法定义一个翻译模块,并在设置 Vue.prototype 的地方和商店模块内的两个地方使用它。
我认为改变 Vuex 原型是一种不好的做法,在这种情况下,它真的没有必要。
只需创建一个名为 localization.js
的文件并在该文件中实例化 i18n 插件。另外导出一个命名函数到 return 同一个 i18n 实例。
// localization.js
const i18n = new VueI18n({ ... });
export const getLocalization = () => i18n;
export default i18n;
然后在您的 Vuex 模块中导入 getLocalization
函数并执行它以获取相同的 i18n
实例并使用它进行翻译。
// vuex-module.js
import Vue from 'vue';
import Vuex from 'vuex';
import { getLocalization } from './localization';
Vue.use(Vuex);
const i18n = getLocalization();
export default {
state: {
criteria: i18n('translation.name'),
},
}
在我的 app.js
文件中,我构建了这个以便我可以在 vue 中使用翻译:
Vue.prototype.trans = string => _.get(window.i18n, string);
这在我的 vue 文件中运行良好:
{{ trans('translation.name') }}
问题是我正在使用 vuex
,我需要翻译模块中的一些内容:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default {
namespaced: true,
state: {
page: 1,
criterias: [
{
name: this.trans('translation.name'),
filter: "life",
active: false
}
}
}
但是这里this.trans('translation.name')
是行不通的。我怎样才能让它发挥作用?
我可以建议您解决方法。您可以使用突变将 criterias
的初始化从 store.js
移动到您的 App.vue
。
store.js
state: {
page: 1,
criterias: []
},
mutations: {
setCriterias(state, payload) {
state.criterias = payload;
},
}
App.vue
beforeMount() {
this.$store.commit( 'setCriterias' , [
{
name: this.trans('translation.name'),
filter: "life",
active: false
}
])
}
由于您的翻译内容 window.i18n
无论如何都是全球性的,为什么不定义另一个 trans
类似于您在商店模块中添加到 Vue.prototype
的方法?
如果您担心以后必须在两个地方编辑此方法,请使用这个方法定义一个翻译模块,并在设置 Vue.prototype 的地方和商店模块内的两个地方使用它。
我认为改变 Vuex 原型是一种不好的做法,在这种情况下,它真的没有必要。
只需创建一个名为 localization.js
的文件并在该文件中实例化 i18n 插件。另外导出一个命名函数到 return 同一个 i18n 实例。
// localization.js
const i18n = new VueI18n({ ... });
export const getLocalization = () => i18n;
export default i18n;
然后在您的 Vuex 模块中导入 getLocalization
函数并执行它以获取相同的 i18n
实例并使用它进行翻译。
// vuex-module.js
import Vue from 'vue';
import Vuex from 'vuex';
import { getLocalization } from './localization';
Vue.use(Vuex);
const i18n = getLocalization();
export default {
state: {
criteria: i18n('translation.name'),
},
}