如何仅更改当前路由 vue-router 中的特定查询参数? [英] How can I change only specific query params in current route vue-router?

查看:89
本文介绍了如何仅更改当前路由 vue-router 中的特定查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to make pagination in Nuxt Js project, so how can I change only page query params in my current route, and keep other query params with there values I have 3 query params :

      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>

推荐答案

你最好的朋友 - 解构作业.JavaScript 文档.

Your best friend - destructuring assignment. JavaScript docs.

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

Here is an example of how to use it in your case:

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

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

Without any additional variables it will look much cleaner:

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

代码执行后,您将拥有 query 覆盖的 page 参数为 100 和其余未修改的参数.

After code execution you will have query with overwritten page parameter to 100 and the remaining untouched parameters.

附注.2019 年 11 月 19 日更新

正如评论中提到的,$route 对象是只读的.更改为 $router.replace$router.push:

As mentioned in comments, $route object is read-only. Change to $router.replace or $router.push:

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

这篇关于如何仅更改当前路由 vue-router 中的特定查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆