如何仅更改当前路由 vue-router 中的特定查询参数?
How can I change only specific query params in current route vue-router?
我尝试在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>
你最好的朋友 - destructuring assignment
。 JavaScript 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,其余参数未被修改。
PS。更新于 19.11.2019
如评论中所述,$route
对象是只读的。
更改为 $router.replace
或 $router.push
:
this.$router.replace({name: path_name, query: {...this.$route.query, page: 100}})
尝试以下方法
this.$router.push({path: this.$route.path, query: { ...this.$route.query, foo: 'bar' }})
是的,这是 Vue 路由器的棘手情况。我已经在此处发布了答案
对于类似的问题
在Nuxt.js中(在vue中会类似):
this.$router.replace(`${this.$route.path}?page=${this.page}`)
this.$router.replace
将用给定的字符串替换当前路径而不将更改推送到历史记录 link
this.route.path
将不带任何 queryString 查询当前路径(使用 this.$route.fullPath
用于带有查询字符串的路由)
我尝试在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>
你最好的朋友 - destructuring assignment
。 JavaScript 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,其余参数未被修改。
PS。更新于 19.11.2019
如评论中所述,$route
对象是只读的。
更改为 $router.replace
或 $router.push
:
this.$router.replace({name: path_name, query: {...this.$route.query, page: 100}})
尝试以下方法
this.$router.push({path: this.$route.path, query: { ...this.$route.query, foo: 'bar' }})
是的,这是 Vue 路由器的棘手情况。我已经在此处发布了答案
在Nuxt.js中(在vue中会类似):
this.$router.replace(`${this.$route.path}?page=${this.page}`)
this.$router.replace
将用给定的字符串替换当前路径而不将更改推送到历史记录 link
this.route.path
将不带任何 queryString 查询当前路径(使用 this.$route.fullPath
用于带有查询字符串的路由)