Borjante
Borjante

Reputation: 10517

Vue-router alias with fixed param

I have this little router over here, and basically I want to have a default language for my site. This means that the same content should be seen if you access www.example.com/about and www.example.com/es/about

I thought an alias would be apropiate for this, however I'm getting a error when tryin to access /about.

[vue-router] missing param for aliased route with path "/:language/about": Expected "language" to be defined

This makes sense as the :language param is not set, is there any way I can implement what I want? Can I set a fixed :language param whenever the user hits the alias?

This is my router.

router = new Router({
  routes: [
    {
      path: '/:language/about',
      alias: '/about'
      component: About
    }
  ]
})

Upvotes: 6

Views: 3994

Answers (2)

David Mold
David Mold

Reputation: 317

Using optional parameters (append ?) will solve this. You won't even need the alias:

router = new Router({
  routes: [
    {
      path: '/:language?/about',
      component: About
    }
  ]
})

Upvotes: 5

Daniel Brown
Daniel Brown

Reputation: 3062

The routes config sets an arbitrary language as the default, if none is provided in the url:

var routes = [
{
    path: '/:lang',
    component: WelcomeComponent,
    children: [
    {
        path: 'hello/:name',
        component: HelloComponent
    }
    ]
},
path: '*',
redirect: '/en'
]

set the lang from the url after each route, if the user makes a direct access to /:lang

router.afterEach((to, from) => {
    Vue.config.lang = to.params.lang
}

I'm pulling this from a forum post that I often reference. It also includes some logic for a language switcher component: https://forum.vuejs.org/t/dynamic-base-in-vue-router/1026/4

Upvotes: 1

Related Questions