vue i18n语言环境未更新

时间:2018-12-26 07:09:59

标签: vue.js nuxt.js vue-i18n

我对Vue很陌生。我想根据环境文件中的值从Firebase检索语言环境。我不清楚必须在哪里对firebase进行异步调用。 (我正在使用nuxt)

store/index.js

import Vuex from 'vuex'
import VueI18n from 'vue-i18n'

const createStore = () => {
  return new Vuex.Store({
    state: {
      locale: process.env.LOCALE,
      localeMessages: ''
    },
    mutations: {
      setLocale(state, locale) {
        state.localeMessages = locale
      }
    },
    actions: {
      getLocaleFromFB(context, { db, app }) {
        let res = db
          .collection('locales')
          .doc(process.env.LOCALE)
          .get()
          .then(function(response) {
            context.commit('setLocale', response.data())
            app.i18n.locale = context.state.locale
            app.i18n.localeMessages = context.state.localeMessages
          })
      }
    }
  })
}

export default createStore

middleware/i18n.js

import firebase from '~/plugins/firebase'
const db = firebase.firestore()
export default function({ isHMR, app, store, route, params, error, redirect }) {
  const defaultLocale = app.i18n.fallbackLocale
  const locale = route.params.lang || defaultLocale
  store.dispatch('getLocaleFromFB', { db, app })
}

plugins/index.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import firebase from '~/plugins/firebase'

Vue.use(VueI18n)

export default ({ app, store }) => {
  // inject our i18n instance into the app root to be used in middleware
  // we assume a store/index.js file has been defined and the variable 'locale' defined on store, we'll go into this in detail in the next code snippet
  const db = firebase.firestore()
  const auth = firebase.auth()
  const currentUser = auth.currentUser
  const settings = {
    timestampsInSnapshots: true
  }
  db.settings(settings)
  app.i18n = new VueI18n({
    //construction a new VueI18n
    locale: store.state.locale,
    fallbackLocale: 'en', //always displays English if translation is not available
    messages: {
      //'locales' directory contains all the translations in the form of json files
      'odisha-english': store.state.localeMessages,
      en: require('~/locales/en.json')
    }
  })
  store.dispatch('getLocaleFromFB', { db, app })

0 个答案:

没有答案