【问题标题】:Vue-router alias with fixed param具有固定参数的 Vue-router 别名
【发布时间】:2017-12-01 16:28:30
【问题描述】:

我这里有一个小路由器,基本上我想为我的网站设置一种默认语言。这意味着如果您访问 www.example.com/about 和 www.example.com/es/about 应该看到相同的内容

我认为别名会适合这个,但是当我尝试访问 /about 时出现错误。

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

这是有道理的,因为没有设置 :language 参数,有什么方法可以实现我想要的吗?每当用户点击别名时,我可以设置一个固定的 :language 参数吗?

这是我的路由器。

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

【问题讨论】:

    标签: vuejs2 vue-router


    【解决方案1】:

    使用可选参数(附加?)可以解决这个问题。你甚至不需要别名:

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

    【讨论】:

      【解决方案2】:

      如果 url 中没有提供任何语言,则路由配置将任意语言设置为默认语言:

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

      如果用户直接访问 /:lang,则在每个路由之后从 url 设置语言

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

      我是从我经常引用的论坛帖子中提取的。它还包括语言切换器组件的一些逻辑:https://forum.vuejs.org/t/dynamic-base-in-vue-router/1026/4

      【讨论】:

        猜你喜欢
        • 2016-10-15
        • 1970-01-01
        • 2018-11-20
        • 2018-01-07
        • 2017-06-20
        • 2020-09-17
        • 2020-05-07
        • 2017-08-13
        相关资源
        最近更新 更多