最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add an i18n locale prefix in Vue router for all the locales except for the default one? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to create a route to add a locale prefix for all the routes, I got it working using this code:

routes: [{
  path: '/:lang',
  ponent: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      ponent: Home
    },
    {
      path: 'about',
      name: 'about',
      ponent: About
    },
    {
      path: 'contact',
      name: 'contact',
      ponent: Contact
    }
  ]
}]

For the default locale en I don't want to set this prefix so params.lang is going to be the full path in this case and not the locale code, so requesting any path without a locale code will render the Home ponent which matches.

So how can I do this? Does a navigation guard like beforeEnter help in this case?

I'm trying to create a route to add a locale prefix for all the routes, I got it working using this code:

routes: [{
  path: '/:lang',
  ponent: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      ponent: Home
    },
    {
      path: 'about',
      name: 'about',
      ponent: About
    },
    {
      path: 'contact',
      name: 'contact',
      ponent: Contact
    }
  ]
}]

For the default locale en I don't want to set this prefix so params.lang is going to be the full path in this case and not the locale code, so requesting any path without a locale code will render the Home ponent which matches.

So how can I do this? Does a navigation guard like beforeEnter help in this case?

Share Improve this question asked Oct 4, 2019 at 16:29 PierrePierre 13.1k8 gold badges49 silver badges67 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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)?',
  ponent: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      ponent: Home
    },
    {
      path: 'about',
      name: 'about',
      ponent: About
    },
    {
      path: 'contact',
      name: 'contact',
      ponent: Contact
    }
  ]
}]

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论