【问题标题】:Nuxt.js + vue-i18n + axios : cant't access to data in pageNuxt.js + vue-i18n + axios:无法访问页面中的数据
【发布时间】:2017-07-03 13:56:21
【问题描述】:

我在 i18n 工作流中的 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>

你能知道这个问题吗?

【问题讨论】:

  • 你是怎么解决这个问题的?

标签: internationalization vuejs2 axios nuxt.js vue-i18n


【解决方案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/');

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

【讨论】:

  • 您仍然从本地文件加载 JSON 数据,而不是从 HTTP URL
猜你喜欢
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2019-07-08
  • 2019-03-03
  • 2020-05-28
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多