【问题标题】:How can I change only specific query params in current route vue-router?如何仅更改当前路由 vue-router 中的特定查询参数?
【发布时间】:2019-06-18 05:18:07
【问题描述】:

我尝试在 Nuxt Js 项目中进行分页, 那么如何仅更改当前路线中的页面查询参数,并保留其他查询参数的值 我有 3 个查询参数:

      this.count = this.$route.query.count ?? 8
      this.page = this.$route.query.page ?? 1
      this.sort_by = this.$route.query.sort_by ?? 'latest'
  <li class="pagination-link" v-for="(page, key) in computed.lastPage" :key="key"
        :class="{ 'active': page === computed.currentPage }">
      <nuxt-link :to="'?page='+page" append
                 :class="{'current-link' : computed.currentPage === page}">
        {{ page }}
      </nuxt-link>
    </li>

【问题讨论】:

  • 谢谢,是的,我做了这个解决方案并且它正在工作,但我正在寻找使用 &lt;nuxt-link&gt;&lt;router-link&gt; 的解决方案

标签: vue-router


【解决方案1】:

你最好的朋友 - destructuring assignmentJavaScript docs.

以下是如何在您的情况下使用它的示例:

let query = this.$route.query;
let newPage = 100;
this.$route.query = {...query, page: newPage};

没有任何额外的变量,它看起来会更干净:

this.$route.query = {...this.$route.query, page: 100};

代码执行后,您将拥有 query 并将 page 参数覆盖为 100 和其余未触及的参数。

附言。更新于 19.11.2019

如 cmets 中所述,$route 对象是只读的。 换成$router.replace$router.push

this.$router.replace({name: path_name, query: {...this.$route.query, page: 100}})

【讨论】:

  • 根据文档,路由对象是只读的,那怎么不抛出类型错误呢?
  • TypeError: Cannot assign to read only property 'params' of object '#&lt;Object&gt;' 肯定是在抛出类型错误。
  • $router.replace 为我工作。我能够使用$router.replace({ query: {} }) 删除所有查询参数
  • 对我来说,使用 Nuxt,this.$router.replace 会导致 NavigationDuplicated: Avoided redundant navigation to current location 错误。但是this.$router.push({ query: { ...this.$route.query, foo: 'bar' } }) 可以正常工作。
【解决方案2】:

试试下面的

this.$router.push({path: this.$route.path, query: { ...this.$route.query, foo: 'bar' }})

【讨论】:

    【解决方案3】:

    是的,这对于 Vue 路由器来说是一个棘手的情况。我已经在这里发布了答案https://stackoverflow.com/a/68822330/8904981 类似的问题

    【讨论】:

      【解决方案4】:

      在 Nuxt.js 中(在 vue 中会类似):

      this.$router.replace(`${this.$route.path}?page=${this.page}`)
      

      this.$router.replace 将用给定的字符串替换当前路径,而不会将更改推送到历史记录link

      this.route.path 将在没有任何 queryString 的情况下查询当前路径(使用 this.$route.fullPath 作为带有查询字符串的路由)

      【讨论】:

        猜你喜欢
        • 2021-02-06
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 2020-08-11
        • 2019-10-18
        • 2021-05-21
        • 2018-03-06
        • 1970-01-01
        相关资源
        最近更新 更多