网址输出中的vue-i18n语言前缀

时间:2018-12-29 06:09:12

标签: vue.js vuejs2 internationalization

有一个可以完全正常工作的站点,其中两种语言都可以正常工作。但是问题在于,更改语言后,URL应该显示该语言,并保留在同一页面上。

我想实现(site.com/ru/about)和(site.com/en/about)

i18n.js

import VueI18n from 'vue-i18n'
import Vue from 'vue'
import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '../constants/trans'
import ru from '../locales/ru.json'

Vue.use(VueI18n)
export const i18n = new VueI18n({
  locale: DEFAULT_LANGUAGE, // set locale
  fallbackLocale: FALLBACK_LANGUAGE,
  messages: { ru }// set locale messages
})

Translation.js

import axios from 'axios'
import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '../constants/trans'
import { i18n } from '../plugins/i18n'

const Trans = {
  get defaultLanguage () {
    return DEFAULT_LANGUAGE
  },
  get supportedLanguages () {
    return SUPPORTED_LANGUAGES
  },
  get currentLanguage () {
    return i18n.locale
  },
  set currentLanguage (lang) {
    i18n.locale = lang
  },
  /**
   * Gets the first supported language that matches the user's
   * @return {String}
   */
  getUserSupportedLang () {
    const userPreferredLang = Trans.getUserLang()

    // Check if user preferred browser lang is supported
    if (Trans.isLangSupported(userPreferredLang.lang)) {
      return userPreferredLang.lang
    }
    // Check if user preferred lang without the ISO is supported
    if (Trans.isLangSupported(userPreferredLang.langNoISO)) {
      return userPreferredLang.langNoISO
    }
    return Trans.defaultLanguage
  },
  /**
   * Returns the users preferred language
   */
  getUserLang () {
    const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage
    return {
      lang: lang,
      langNoISO: lang.split('-')[0]
    }
  },
  /**
   * Sets the language to various services (axios, the html tag etc)
   * @param {String} lang
   * @return {String} lang
   */
  setI18nLanguageInServices (lang) {
    Trans.currentLanguage = lang
    axios.defaults.headers.common['Accept-Language'] = lang
    document.querySelector('html').setAttribute('lang', lang)
    return lang
  },
  /**
   * Loads new translation messages and changes the language when finished
   * @param lang
   * @return {Promise<any>}
   */
  changeLanguage (lang) {
    if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported'))
    if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior
    return Trans.loadLanguageFile(lang).then(msgs => {
      i18n.setLocaleMessage(lang, msgs.default || msgs)
      return Trans.setI18nLanguageInServices(lang)
    })
  },
  /**
   * Async loads a translation file
   * @param lang
   * @return {Promise<*>|*}
   */
  loadLanguageFile (lang) {
    return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`)
  },
  /**
   * Checks if a lang is supported
   * @param {String} lang
   * @return {boolean}
   */
  isLangSupported (lang) {
    return Trans.supportedLanguages.includes(lang)
  },
  /**
   * Checks if the route's param is supported, if not, redirects to the first supported one.
   * @param {Route} to
   * @param {Route} from
   * @param {Function} next
   * @return {*}
   */
  routeMiddleware (to, from, next) {
    // Load async message files here
    const lang = to.params.lang
    if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang())
    return Trans.changeLanguage(lang).then(() => next())
  }
}

export { Trans }

index.js(路由器)

....
import {i18n} from '../plugins/i18n'
import {DEFAULT_LANGUAGE} from '../constants/trans.js'


Vue.use(Router);
Vue.use(Meta)

export default new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Main',
            component: Main
        },
        {
            path: '/calculator',
            name: 'Calculator',
            component: PageCalculator
        },
        {
            path: '/portfolio',
            name: 'Portfolio',
            component: PageProject
        },
        {
            path: '/contact',
            name: 'Contact',
            component: PageContact
        },
        {
            path: '*',
            redirect: '/'
        }

    ]
});

我试图这样开始..然后我不知道该怎么办。

export default new Router({
    routes: [
        {
            path: '/',
            redirect: `/${DEFAULT_LANGUAGE}`,
        },
    {
    path: '/:locale',
            component: {
        template: '<router-view />',
    },
    children: [
        {
            path: '/',
            name: 'Main',
            component: Main
        },
        {
            path: 'calculator',
            name: 'Calculator',
            component: PageCalculator
        },
        {
            path: 'portfolio',
            name: 'Portfolio',
            component: PageProject
        },
        {
            path: 'contact',
            name: 'Contact',
            component: PageContact
        },
        {
            path: '*',
            redirect: '/'
        }
    ],
},
],
})

0 个答案:

没有答案