vue.js - Vue-i18n - 来自 http 请求的动态本地化问题
问题描述
我正在尝试从 HTTP 调用加载本地化,因为我希望语言是动态的和可管理的,而不是随应用程序一起提供。
我使用 SSR 示例和我自己的一些实现做了一些工作。但是在初始渲染时,语言不会加载。当更改路由客户端时,事情正在更新。
i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import en from './en.json'
import ar from './ar.json'
import axios from 'axios'
Vue.use(VueI18n)
const fallbackLocale = 'en'
let defaultLocale = 'ar'
export const i18n = new VueI18n({
locale: defaultLocale, // set locale
fallbackLocale: fallbackLocale,
messages: {
'en': en
}
})
export function createI18n () {
return i18n
}
路由器 - router.beforeEach
router.beforeEach((to, from, next) => {
if (router.app.$store) {
router.app.$store
.dispatch('getI18nData')
.then(function(){
router.app.$i18n.setLocaleMessage('ar',router.app.$store.getters.getLocale)
return next()
})
.catch(() => console.log('getI18nData-error'))
} else {
next()
}
})
存储操作 - 获取语言环境
getI18nData ({ commit }) {
try {
axios.get('http://localhost:8080/lang?lang=ar')
.then(function (response) {
let locale = response.data
commit('setLocale', { locale })
})
.catch(function (error) {
console.log('Error:getI18nData')
})
} catch (error) {
console.error(error);
}
}
结果:
i18nrouter.beforeEach
在它应该在之后初始化的地方初始化router.beforeEach
。
解决方案
好吧,说得更详细一点:你不想将 try/catch 与你的 Promise 链混合,但你需要返回一个 Promise fromgetI18nData
或 dispatch 不会等待。所以你要么:
getI18nData ({ commit }) {
// axios.get() returns a promise already, so we can just return the whole thing:
return axios
.get('http://localhost:8080/lang?lang=ar')
.then(function (response) {
let locale = response.data
commit('setLocale', { locale })
})
.catch(function (error) {
console.log('Error:getI18nData')
});
}
或者您使用 async/await (允许 try/catch):
async getI18nData ({ commit }) {
try {
let response = await axios.get('http://localhost:8080/lang?lang=ar');
let locale = response.data
commit('setLocale', { locale })
} catch (error) {
console.error(error);
}
}
我想补充一点,我确实更喜欢 async/await 选项,但在 vuex-land 中,它通常会导致您必须将所有内容都设置为 async/await(如果您使用嵌套调度调用)。因此,根据您的代码库的其余部分,仅返回承诺可能会更容易。
推荐阅读
- python - 我收到错误:“NoneType”对象没有“get”属性,我不知道如何解决上述问题
- vb.net - 数据表和两行排序
- r - 如何在 R 中将 '2020-10-31T00:00:00.0000000' 从因子转换为日期?
- java - 使用 Selenium 和 Java 进行可视化测试
- java - androidx.preference.SwitchPreference Android Studio 的问题
- javascript - 铬扩展。JS 适用于弹出窗口而不是主窗口
- jenkins - Kubernetes 插件显示警告消息 WatchConnectionManager$1#onFailure
- c++ - 返回默认模板的优雅解决方案
- python - 在 Windows 10 中安装 Pyaudio 时出错
- html - 滚动到本地锚点在第二次单击时向后滚动