【问题标题】:Folders/files structure for nuxt query string parametersnuxt 查询字符串参数的文件夹/文件结构
【发布时间】:2020-07-21 18:32:21
【问题描述】:

应该如何构建文件和文件夹,以便它们使用 URL 查询字符串参数而不是常规参数?

例子:

网址参数:

文件夹结构:

pages/
---|comments/
------|_id.vue

这种结构导致这条路线:

pages/comments/page/1

需要如何构建文件夹/文件,以便我的路线如下所示?

网址查询字符串参数:

pages/comments?page=1

【问题讨论】:

  • 我认为 url 查询不是路由的一部分,因此您只需使用 /pages/comments 路由,然后稍后在组件中访问查询,例如this.$router.query.page。见相关nuxtjs.org/guide/routing#locally-accessing-route-params
  • 在 created() 钩子上使用 this.$router.query.page 设置页面时,它不会显示在浏览器的 URL 中,而是附加到 $router 对象。
  • 对于导航,您应该使用 <router-link :to='/pages/comments?page=1'><router-link :to='{ name: 'commentName', query: { page: 1 } }'>this.$router.push('/pages/comments?page=1') 或 ...
  • 是的,但我正在尝试设置初始页面加载参数。我使用this.$router.push({path: this.$route.path,query: { page: this.currentPage }}) 取得了一些成功

标签: vue.js vuejs2 nuxt.js vue-router


【解决方案1】:

我得出的结论:

  • 对于索引页面,初始加载时不要查询第一页的字符串参数。

  • 使用以下方法观察查询字符串的变化: watch: { '$route.query': '$fetch' }(这将在每个页面更改或查询字符串中的任何其他内容上运行 fetch 方法)

  • 由于 fetch() 在每个页面更改上运行,您需要使用 this.$route.query.page(在我的情况下为页面)在您的请求中包含查询字符串参数

  • 您还需要确保您的页面始终设置为某个数字,即使您在索引页面上并且未应用任何查询参数:

    if (this.$route.query.page) {
       this.currentPage = this.$route.query.page
    } else {
    this.currentPage = 1
    } 
    

另外,如果您需要路由到附加参数的页面,请使用:
this.$router.push({path: this.$route.path,query: { page: 1}})

使用 nuxt-link
<nuxt-link :to="{ name: '/', params: { page: 1 }}"></nuxt-link>:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多