如何在Vue路由器中为除默认语言之外的所有语言环境添加i18n语言环境前缀?

Pie*_*rre 4 javascript vue.js vue-router vue-i18n

我正在尝试创建一个路由来为所有路由添加语言环境前缀,我使用以下代码使其工作:

routes: [{
  path: '/:lang',
  component: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      component: Home
    },
    {
      path: 'about',
      name: 'about',
      component: About
    },
    {
      path: 'contact',
      name: 'contact',
      component: Contact
    }
  ]
}]
Run Code Online (Sandbox Code Playgroud)

对于默认语言环境,en我不想设置此前缀,因此params.lang在这种情况下将是完整路径而不是语言环境代码,因此请求没有语言环境代码的任何路径将呈现Home匹配的组件。

那么我该怎么做呢?beforeEnter在这种情况下,导航守卫喜欢帮助吗?

max*_*xim 5

Actually you can do it without navigation guards. The main goal here is to let the router understand when you have a url without :lang parameter. To distinguish between the language prefixes and the actual paths you could use a regex pattern for the :lang param like: (de|fr|en|zu) (whatever list of codes is suitable for you). And make the :lang to be an optional ?.

So something like this should work: path: '/:lang(de|fr|en|zu)?' At least it works for me :) ...

So now if you request /about or /de/about both would match About.. however the first one will have params.lang === undefined. So I guess whenever you set your locale you can do: const locale = this.$route.params.lang || 'en'

here is the documentation for Advanced Matching Patterns

routes: [{
  path: '/:lang(de|fr|en|zu)?',
  component: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      component: Home
    },
    {
      path: 'about',
      name: 'about',
      component: About
    },
    {
      path: 'contact',
      name: 'contact',
      component: Contact
    }
  ]
}]
Run Code Online (Sandbox Code Playgroud)