繁体   English   中英

如何在nuxt中为每种可用语言创建动态链接?

[英]How to create dynamic links in nuxt for each available language?

对于我的项目,我将 Nuxt 与 i18n 一起使用。 在 .env 文件中,我创建了一个包含所有可用语言的数组。 现在在 nuxt.config 中,我想为每种可用语言配置 about 菜单。 about 应该是一个对象,包含语言环境和菜单名称,例如:

about: {
  "nl-NL": process.env.ABOUT_NAME[0],
  en: process.env.ABOUT_NAME[1]
}

我不希望可用的语言被硬编码,它们应该是动态的。 因此,对于 AVAILABLE_LOCALE.split(",") 中的每种语言,向 about 对象添加属性。

我怎样才能做到这一点? 现在我有这个代码:

nuxt.config.js

publicRuntimeConfig: {
  ABOUT: Array.from(process.env.ABOUT_NAME).forEach(lang => {
    this.language = lang;
  }),
}

.env

AVAILABLE_LOCALE='nl-NL,en,es'
ABOUT_NAME='Over ons,About us,Sobre nosotros'

我以前在我的nuxt项目中直接使用vue-i18n ,效果很好

yarn add vue-i18n

.env

APP_LOCALE=zh-CN
LOCALES_AVAILABLE=en,zh-CN,ja

配置文件

export default {
    locale: {
        default: process.env.APP_LOCALE,
        available: process.env.LOCALES_AVAILABLE.split(',')
    }
};

nuxt.config.js

    plugins:[
        ...
        '~/plugins/i18n',
    ],
    buildModules: [
        ...
        ['@nuxtjs/dotenv', {
            only: [
                ...
                'APP_LOCALE',
                'LOCALES_AVAILABLE',
            ]
        }]
    ],
    router: {
        middleware: [
            ...
            'locale',
        ]
    },

中间件/locale.js

import config from '~/config';

export default function ({ isHMR, app, store, route, params, error, redirect, $axios }) {
    // If middleware is called from hot module replacement, ignore it
    if (isHMR) { return }

    const locale = params.locale || config.locale.default,
          defaultLocale = config.locale.default,
          localesAvailable = config.locale.available;

    if (localesAvailable.includes(locale)) {
        app.i18n.locale = locale;
        
        // if you don't use @nuxtjs/axios, please comment this(also the $axios in params)
        $axios.setHeader('Accept-Language', locale);

        if (store.state.locale.locale !== locale) {
            store.commit('locale/setLocale', locale);
        }
    }
    else{
        return error({ message: 'Page Not Found', statusCode: 404 });
    }

    // If route is /{APP_LOCALE}/... -> redirect to /...
    if (locale === defaultLocale && route.fullPath.indexOf(`/${defaultLocale}`) === 0) {
        const to_replace = `^/${defaultLocale}` + (route.fullPath.indexOf(`/${defaultLocale}/`) === 0 ? '/' : '');
        const re = new RegExp(to_replace);
        return redirect(
            route.fullPath.replace(re, '/')
        );
    }
}

插件/i18n.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import config from '~/config.js';

Vue.use(VueI18n);

let messages = Object;

config.locale.available.forEach(locale => {
    messages[locale] = require(`~/locales/${locale}.json`);
});

export default ({ app, store }) => {
    app.i18n = new VueI18n({
        locale: store.state.locale.locale,
        messages: messages
    });
}

在您的 nuxt 项目中创建一个新目录: locales

--locales
  |--en.json
  |--zh-CN.json
  |--ja.json

en.json示例:

{
    "sign_in": "sign in",
    "sign_up": "sign up",
    "sign_out": "sign out"
}

商店/locale.js

import config from '~/config.js';

export const namespace = true;

export const state = () => ({
    locale: config.locale.default,
    locales_available: config.locale.available,
    default_locale: config.locale.default
});

export const getters = {
    locale: state => state.locale
};

export const mutations = {
    setLocale(state, locale){
        state.locale = locale;
    }
};

是我得到的,您可以在页面底部更改语言


示例中的某些错误,只需修复它

修复! 这是对我有用的结果:

    PAGE: {
      NAME: JSON.parse(
        JSON.stringify(
          process.env.PAGE_NAME.split(",")
            .map(function(translation) {
              const index = process.env.PAGE_NAME.split(",").indexOf(
                translation
              );
              let newObject = {};
              newObject.id = index;
              newObject.language = process.env.AVAILABLE_LOCALE.split(",")[
                index
              ];
              newObject.name = translation;
              return newObject;
            })
            .reduce((acc, obj) => {
              let { name, language } = obj;
              return { ...acc, [language.toUpperCase()]: name };
            }, {})
        )
      ),
      URL: JSON.parse(
        JSON.stringify(
          process.env.PAGE_NAME.split(",")
            .map(function(translation) {
              const index = process.env.PAGE_NAME.split(",").indexOf(
                translation
              );
              let newObject = {};
              newObject.id = index;
              newObject.language = process.env.AVAILABLE_LOCALE.split(",")[
                index
              ];
              newObject.name = translation;
              return newObject;
            })
            .reduce((acc, obj) => {
              let { name, language } = obj;
              return {
                ...acc,
                [language.toUpperCase()]: name
                  .replace(/\s+/g, "-")
                  .toLowerCase()
              };
            }, {})
        )
      )
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM