2

我很难在 i18n worflow 中的 NuxtJS 中显示数据。

这是两个文件,我肯定错过了配置中的一些内容:

插件 > i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import axios from 'axios'

Vue.use(VueI18n, axios)

export default ({ app, store }) => {
  // Set i18n instance on app
  // This way we can use it in middleware and pages asyncData/fetch
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: 'en',
    messages: {
      'en': axios({
        method: 'get',
        url: 'https://jsonplaceholder.typicode.com/posts'
      }).then((res) => { return { posts: res.data } }),
      'fr': 'hello'
    }
  })
}

页面 > blog.vue

<template>
  <div class="Content">
    <div class="container">
        <ul>
            <li v-for="post in posts">
                {{ $t('post.title') }}
            </li>
        </ul>
    </div>
  </div>
</template>

<script>
export default {
  data: () => ({
    posts: []
  })
}
</script>

你能知道这个问题吗?

4

1 回答 1

1

根据新的 vue-i18n 文档,您必须使用i18n.setLocaleMessage来实现动态语言环境。这是我在 Nuxt 的做法

~/plugins/vuex-persistedstate.js

import createPersistedState from 'vuex-persistedstate';
import acceptLanguage from 'accept-language';
import * as acceptLanguageList from '~/assets/static/lang.json';
acceptLanguage.languages(acceptLanguageList);

export default async ({ app, store }) => {
  createPersistedState({
    key: 'setting',
    paths: ['local'],
  })(store);

  const lang = store.state.local.ui_lang;
  const avail = acceptLanguage.get(navigator.language);

  // wait file downloading or page will load 'no locale'
  await app.i18n.loadLocaleMessage(lang || avail, '/locales/');
};

~/plugins/i18n.js

import axios from 'axios';

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

export default ({ app }) => {
  /** 
   * silentTranslationWarn will disable warning when
   * loading locale without a preloaded locale
    */
  app.i18n = new VueI18n({ silentTranslationWarn: true });
  app.i18n.loadLocaleMessage = async (locale, path) => {
    let data = null;
    try {
      const file = await axios.get(`${path + locale}.json`);
      data = await file.data;
      app.i18n.setLocaleMessage(locale, data);
      app.i18n.locale = locale;
    } catch (e) {
      // do nothing
    }
    return data;
  };
};

~/nuxt.config.js

/* ... */
plugins: [
    '~/plugins/i18n.js',
    { src: '~/plugins/vuex-persistedstate.js', ssr: false },
],
/* ... */

然后你的页面(哈巴狗)

your-component {{$t(content)}}

您可以通过以下方式动态更改您的语言环境

this.$i18n.locale = locale;
await this.$i18n.loadLocaleMessage(locale, '/locales/');

我很痛苦,没有时间编辑更多

于 2018-02-24T20:24:27.233 回答