【问题标题】:Browser navigation not loading component in Vue.js app浏览器导航未在 Vue.js 应用程序中加载组件
【发布时间】:2018-12-17 01:40:57
【问题描述】:

我正在用 Vue.js 构建一个单页应用程序。目前,在您尝试使用浏览器导航按钮(后退/前进)之前,网站导航正常工作。

当尝试使用这些导航时,不会创建任何页面。 URL 将更改,但不会加载任何组件,除非您备份到加载组件的基本 URL。

模板根本没有加载,我也有没有显示错误的 ESlint。

这是我的路由器 index.js:

Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'search',
      component: Search,
    },
    {
      path: '/results?terms=:terms',
      name: 'results',
      component: Results,
    },
    {
      path: '/review?id=:id',
      name: 'review',
      component: Review,
    },
  ],
});

我使用以下方式更改页面:this.$router.push({ name: 'results', params: { terms: this.terms } });

我对 Vue 很陌生,所以我很确定我犯了一个愚蠢的错误,但我花了太多时间试图解决这个问题,所以一些帮助会很好。谢谢。

【问题讨论】:

  • 你的应用运行如何?
  • 我目前正在使用 npm run dev 在本地运行它
  • 您的浏览器控制台有错误吗?运行npm run dev 的终端/控制台怎么样?
  • 两个位置都没有错误/警告。

标签: javascript vue.js


【解决方案1】:

这里的问题是路由参数不应该作为查询字符串参数传递。它们仅供在 URL path 中使用。

由于某种原因,路由器能够处理编程导航,但不能处理直接 URL 加载。

如果你仍然想使用查询字符串(而不是路径参数),我建议你改成这样......

  1. 为你的组件定义 props,例如

    export default {
      name: 'Results',
      props: ['terms'],
      // etc
    
  2. 在路由定义中将查询字符串变量作为道具传递

    {
      name: 'results',
      path: '/results',
      component: Results,
      props: route => ({ terms: route.query.terms })
    }
    
  3. 在程序化导航中设置 query 而不是 params

    this.$router.push({ name: 'results', query: { terms: this.terms } })
    

【讨论】:

  • 非常感谢,实际上我只是想通了。现在一切正常。
  • 这个解决方案仍然有效。
猜你喜欢
  • 2013-08-26
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2021-12-25
相关资源
最近更新 更多