259

I am trying to set query params with Vue-router when changing input fields, I don't want to navigate to some other page but just want to modify URL query params on the same page, I am doing this:

this.$router.replace({ query: { q1: "q1" } })

But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it?


Edited:

Here is my router code:

export default new Router({
  mode: 'history',
  scrollBehavior: (to, from, savedPosition)  => {
    if (to.hash) {
      return {selector: to.hash}
    } else {
      return {x: 0, y: 0}
    }
  },
  routes: [
    ....... 
    { path: '/user/:id', component: UserView },
  ]
})

17 Answers 17

299

Here is the example in docs:

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

Ref: https://router.vuejs.org/guide/essentials/navigation.html

As mentioned in those docs, router.replace works like router.push

So, you seem to have it right in your sample code in question. But I think you may need to include either name or path parameter also, so that the router has some route to navigate to. Without a name or path, it does not look very meaningful.

This is my current understanding now:

  • query is optional for router - some additional info for the component to construct the view
  • name or path is mandatory - it decides what component to show in your <router-view>.

That might be the missing thing in your sample code.

EDIT: Additional details after comments

Have you tried using named routes in this case? You have dynamic routes, and it is easier to provide params and query separately:

routes: [
    { name: 'user-view', path: '/user/:id', component: UserView },
    // other routes
]

and then in your methods:

this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })

Technically there is no difference between the above and this.$router.replace({path: "/user/123", query:{q1: "q1"}}), but it is easier to supply dynamic params on named routes than composing the route string. In either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.

After you are inside the route, you can fetch your dynamic params as this.$route.params.id and your query params as this.$route.query.q1.

11
  • 1
    I tried giving the path also, but this did not stop scrolling to the top of the page, I have edited the question with router options also, may be there is some change needed there.
    – Saurabh
    Commented Nov 3, 2016 at 6:10
  • Is your query param intended to scroll to the right place in the document? Like your other question on anchor tags? Commented Nov 3, 2016 at 6:57
  • 1
    No, I just want to add the query param in URL, I don't want any scroll here.
    – Saurabh
    Commented Nov 3, 2016 at 7:31
  • I just tested the options in my local setup, the query params work normally. I am able to navigate to new route and access query params as shown in my updated answer. So, the problem is - you do not want it to scroll? Or the problem is the entire app refreshing again? Commented Nov 3, 2016 at 9:05
  • 1
    so I am on the same page, when I select some input, I want to add them in the URL, but when I do it, scroll happens. Scroll is the issue for me. I am not trying to navigate to other page, I just want to be on same page and add/modify url query params seemlessly.
    – Saurabh
    Commented Nov 3, 2016 at 10:56
40

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

1
  • In Vue3 setup api you need to use window.history.pushState Commented Oct 26, 2022 at 12:08
30

Okay so i've been trying to add a param to my existing url wich already have params for a week now lol, original url: http://localhost:3000/somelink?param1=test1 i've been trying with:

this.$router.push({path: this.$route.path, query: {param2: test2} });

this code would juste remove param1 and becomes http://localhost:3000/somelink?param2=test2

to solve this issue i used fullPath

this.$router.push({path: this.$route.fullPath, query: {param2: test2} });

now i successfully added params over old params nd the result is

http://localhost:3000/somelink?param1=test1&param2=test2

30

Actually you can push query like this: this.$router.push({query: {plan: 'private'}})

Based on: https://github.com/vuejs/vue-router/issues/1631

4
  • 49
    "But this also refreshes the page"
    – digout
    Commented Mar 7, 2019 at 14:49
  • 1
    Not sure about Vue2 but works like a charm in Vue3 (without page-refresh) Commented Dec 30, 2021 at 10:46
  • 1
    @ArnovanOordt It also reloads the page in Vue 3. Commented Sep 7, 2022 at 7:55
  • 2
    There is a misunderstanding here about what "refreshes the page" means here. A hard refresh (like F5) and an actual vue-router client-side navigation are 2 different things. Here, jean's solution does not trigger a "page hard refresh", meanwhile it will trigger a vue-router navigation and possible mount/unmount specific components. Things that OP do not want indeed.
    – kissu
    Commented Dec 3, 2022 at 17:28
22

If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.

This works, since you are making an unreferenced copy:

  const query = Object.assign({}, this.$route.query);
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated error:

  const query = this.$route.query;
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.

  const { page, limit, ...otherParams } = this.$route.query;
  await this.$router.push(Object.assign({
    page: page,
    limit: rowsPerPage
  }, otherParams));
);

Note, while the above example is for push(), this works with replace() too.

Tested with vue-router 3.1.6.

15

Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.

const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
4
  • How do you access this.$route.query in vue3 composition API ? Commented Jun 14, 2022 at 13:16
  • @iiiml0sto1 for accessing the root element in Composition API i use import { getCurrentInstance } from 'vue' on top and in the code const root = getCurrentInstance(); and var query = root.proxy.$route.query
    – stif
    Commented Oct 13, 2022 at 10:09
  • @iiiml0sto1 check that one: stackoverflow.com/a/67357142/8816585
    – kissu
    Commented Dec 3, 2022 at 17:30
  • 1
    I would recomend import { useRoute } from 'vue-router'; and then const route = useRoute(); and console.log('query', route.query);
    – agm1984
    Commented Feb 13, 2023 at 19:00
9

My solution, no refreshing the page and no error Avoided redundant navigation to current location

    this.$router.replace(
      {
        query: Object.assign({ ...this.$route.query }, { newParam: 'value' }),
      },
      () => {}
    )
1
  • This causes page to scroll to top.
    – yooneskh
    Commented May 24, 2021 at 0:06
7

You could also just use the browser window.history.replaceState API. It doesn't remount any components and doesn't cause redundant navigation.

window.history.replaceState(null, '', '?query=myquery');

More info here.

2
  • 1
    second argument should be a string, so window.history.replaceState(null, '', '?query=myquery');
    – commonpike
    Commented May 28, 2022 at 12:36
  • The Vue-router will throw a history state missing warning. So instead of null, pass the history.state like: window.history.replaceState(history.state, '', '?query=myquery'); Commented Jan 23, 2023 at 21:11
6
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })
6
  • 2
    I liked this answer the best. Unfortunately this causes Error: Avoided redundant navigation to current location
    – Max Coplan
    Commented Jun 25, 2020 at 16:49
  • 1
    Fix: this.$router.push({ query: Object.assign({...this.$route.query}, { new: 'param' }) })
    – Max Coplan
    Commented Jun 25, 2020 at 16:59
  • 3
    But now that I think about it you can just do this.$router.push({ query: {...this.$route.query,new: 'param'},) })
    – Max Coplan
    Commented Jun 25, 2020 at 17:01
  • How do you access this.$route.query in vue3 composition API ? Commented Jun 14, 2022 at 13:15
  • 1
    @iiiml0sto1 Something like: js import { useRouter, useRoute } from 'vue-router'; const router = useRouter(); const route = useRoute(); // then in your logic const query = Object.assign(route.value.query, { new: 'param' }); router.value.push({ query }); Commented Jun 17, 2022 at 22:28
5

For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).

an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });
3

To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

    setQuery(query){
        let obj = Object.assign({}, this.$route.query);

        Object.keys(query).forEach(key => {
            let value = query[key];
            if(value){
                obj[key] = value
            } else {
                delete obj[key]
            }
        })
        this.$router.replace({
            ...this.$router.currentRoute,
            query: obj
        })
    },

    removeQuery(queryNameArray){
        let obj = {}
        queryNameArray.forEach(key => {
            obj[key] = null
        })
        this.setQuery(obj)
    },
3

I normally use the history object for this. It also does not reload the page.

Example:

history.pushState({}, '', 
                `/pagepath/path?query=${this.myQueryParam}`);
3

The vue router keeps reloading the page on update, the best solution is

  const url = new URL(window.location);
  url.searchParams.set('q', 'q');
  window.history.pushState({}, '', url);
        
3

This is the equivalent using the Composition API

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

router.push({ path: 'register', query: { plan: 'private' }})
</script>

You can also use the Vue devtools just to be sure that it's working as expected (by inspecting the given route you're on) as shown here: https://stackoverflow.com/a/74136917/8816585


Update

That will meanwhile mount/unmount components. Some vanilla JS solution is still the best way to go for that purpose.

2

I know that this question has been answered a bunch of times in the last 7 years, but here is the late 2023 solution that I am using and that works for me.

First you have to make sure that router view has a :key: <RouterView :key="$route.fullPath" />

this will make sure that the current route will reload if there is ANY change in the current browser URL.

Next, when something happens within the page - you just have to append any non-breaking value to a current URL. I simply append current unix timestamp as a query parameter value, i.e.:

import { useRouter} from 'vue-router'

const onClick = async () => {
  router.replace({
        name: 'order',
        params: { id: 1 }, // params
        query: { ver: new Date().getTime() } // query params
      })
}

the final url will look something like: http://localhost:5173/order/1?ts=1699792710908

by using the router.replace instead of router.push - you are basically replacing the current path on the browser's history stack. So when the user clicks back - he will instead be forwarded to some previous page of the past instead of the same page but without the timestamp query parameter in the url. Hope it makes sense.

I am yet to find any shortcomings of this approach, so please let me know in the comments if it has any drawbacks.

p.s. is valid for vuejs version 3

1

With RouterLink

//With RouterLink
<router-link 
  :to="{name:"router-name", prams:{paramName: paramValue}}"
>
Route Text
</router-link>

//With Methods

methods(){
  this.$router.push({name:'route-name', params:{paramName: paramValue}})
}

With Methods

methods(){
  this.$router.push({name:'route-name', params:{paramName, paramValue}})
}
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 19, 2022 at 11:42
1

you should use router.push here is example :

this.$router.push({   
    path: '/your-path',   
    query: { key1: 'value1', key2: 'value2' }   
}); 

also You can set query parameters directly in the template using <router-link> here is example :

<router-link :to="{ path: '/your-path', query: { key1: 'value1', key2: 'value2' }}">  
  Path      
</router-link>  

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.