【问题标题】:Empty optional parameter will fall to home path空的可选参数将落入主路径
【发布时间】:2017-06-27 10:08:42
【问题描述】:

这些是我的路线:

import Search from './Search.vue'
import Home from './Home.vue'
export const routes = [
    {path : '/', name: 'Home', component: Home},
    {path : '/search/:keyword?', name: 'Search', component: Search}, //i put ? in the end of path to make this optional.
];

这是路由到搜索页面的操作:

this.$router.push({
   name : 'Search',
   params : {
      keyword : this.keywords // set this to empty string
   },
   query: {
       page : 1
   }
})

如果this.keywords''(一个空字符串),它将返回到gamedb.com/(home)。如果this.keywords中有一些字母,路径会转到gamedb.com/search/this-is-the-keyword

我的预期行为是当this.keywords 为空时,路径将转到gamedb.com/search

我的console.log 显示:

[vue-router] 缺少命名路由“搜索”的参数:预期 "keyword" 匹配 "[^/]+?",但收到 ""

我不是已经在路线的尽头放了一个问号吗?我的代码有什么问题?

【问题讨论】:

    标签: javascript vuejs2 vue-router


    【解决方案1】:

    您是正确的,将问号 ? 附加到路由路径中的参数将使该参数成为可选参数。但是,这仅仅意味着如果你根本不传递keyword 参数,Vue Router 就不会抱怨。

    您正在传递一个keyword 参数,但它是一个空字符串。 URL 参数不能为空字符串,因此您会收到错误消息。

    仅当this.keywords 的值不为空时,您才需要将params 对象添加到传递给this.$router.push 的选项中:

    this.$router.push({
      name : 'Search',
      params: (this.keywords.length > 0) ? { keyword: this.keywords } : {},
      query: {
        page : 1
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2011-10-12
      • 2018-05-13
      • 2015-03-28
      • 1970-01-01
      • 2018-03-20
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多