vue.js中具有语言环境的前缀路由(使用vue-i18n) [英] Prefix routes with locale in vue.js (using vue-i18n)

查看:740
本文介绍了vue.js中具有语言环境的前缀路由(使用vue-i18n)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个locale.js文件,该文件负责定义用户区域设置.在这里:

I have a locale.js file which is responsible for defining user locale. Here it is:

import store from '@/vuex/index'

let locale

const defaultLocale = 'en_US'

if (store.getters['auth/authenticated']) {
  locale = store.getters['auth/currentUser'].locale || defaultLocale
} else {
  if (localStorage.getItem('locale')) {
    locale = localStorage.getItem('locale')
  } else {
    locale = defaultLocale
  }
}

export default locale

此外,我还有一个i18n.js文件,该文件负责制作我在初始化应用程序时使用的i18n实例.

Also I have a i18n.js file which is responsible for making i18n instance which I use when I init my app.

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from '@/services/locale'

Vue.use(VueI18n)

const fallbackLocale = 'en_US'

let i18n = new VueI18n({
  locale,
  fallbackLocale,
})

i18n.setLocaleMessage('ru_RU', require('@/lang/ru_RU.json'))
i18n.setLocaleMessage('en_US', require('@/lang/en_US.json'))

export { i18n }

现在,我认为使用以语言环境为前缀的URL(例如/en/profile/ru/profile)会更方便.这样,我可以与已经设置的语言环境共享一个链接.

Now I think that it'd be more convenient to have URLs prefixed with locale, like /en/profile or /ru/profile. This way I can share a link with locale which would be already set.

虽然不确定如何执行此操作.将所有路由设置为子路径并放置/:locale?并不是很方便,因为路由器尚未初始化(初始化根应用程序实例时,我同时传递了i18nrouter实例).

Not sure how do to this though. Making all routes child and put /:locale? is not that convenient because router is not yet initialized (I pass i18n and router instances simultaneously when initing root app instance).

如何实现这一目标,最好的方法是什么?

How can I achieve that, what would be the best approach?

推荐答案

您可以实现路由器

routes: [{
    path: '/:lang',
    children: [
      {
        path: 'home'
        component: Home
      },
      {
        path: 'about',
        component: About
      },
      {
        path: 'contactus',
        component: ContactUs
      }
    ]
  }]

并在beforeEach挂钩中设置locale

// use beforeEach route guard to set the language
router.beforeEach((to, from, next) => {

  // use the language from the routing param or default language
  let language = to.params.lang;
  if (!language) {
    language = 'en';
  }

  // set the current language for vuex-i18n. note that translation data
  // for the language might need to be loaded first
  Vue.i18n.set(language);
  next();

});

这篇关于vue.js中具有语言环境的前缀路由(使用vue-i18n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆