Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change only specific query params in current route vue-router?

Tags:

vue-router

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>
like image 289
Anass Ez-zouaine Avatar asked Jan 24 '19 12:01

Anass Ez-zouaine


2 Answers

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};

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

PS. Updated on 19.11.2019

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}})
like image 62
AndrewShmig Avatar answered Oct 28 '22 09:10

AndrewShmig


Try the following

this.$router.push({path: this.$route.path, query: { ...this.$route.query, foo: 'bar' }})
like image 32
Hossein Bajan Avatar answered Oct 28 '22 09:10

Hossein Bajan