vue.js - Vue-i18n - 来自 http 请求的动态本地化问题

标签 vue.js vue-i18n vue-ssr

我正在尝试从 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);
   }
 }

调查结果: i18n 在 router.beforeEach 之前初始化,而它应该在 router.beforeEach 之后初始化。

Github Issue Link

最佳答案

好吧,更详细一点:您不想将 try/catch 与您的 promise 链混合在一起,但您需要从 getI18nData 返回一个 promise ,否则调度将不会等待。所以你要么:

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(如果您使用嵌套调度调用)。因此,根据代码库的其余部分,返回 promise 可能会更容易。

关于vue.js - Vue-i18n - 来自 http 请求的动态本地化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781934/

相关文章:

javascript - v-on 处理程序中的错误 : "ReferenceError: i18n is not defined"

vue.js - 在 cloudflare workers 上运行 vue3 ssr

javascript - Vue.js - 鼠标修饰符有什么用?

docker - VueJS Nginx 和 docker 设置 - 本地 ERR_EMPTY_RESPONSE

javascript - 如何在 Vue 3 + i18n 中导入多个语言环境 json 文件?

javascript - 如何使用 VueI18n 进行基于组件实例的国际化?

vue.js - 使用 Vue SSR 渲染页面时的动态 publicPath

javascript - Nuxt.JS 没有按我的需要渲染 block

javascript - 为什么它只对原来设置的mount数据加/减7