ChatGPT解决这个技术问题 Extra ChatGPT

How to set URL query params in Vue with Vue-Router

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 like 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 },
  ]
})

M
Mani

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/en/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 .

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. But 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.


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.
Is your query param intended to scroll to the right place in the document? Like your other question on anchor tags?
No, I just want to add the query param in URL, I don't want any scroll here.
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?
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.
d
doppelgreener

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.


j
jean d'arme

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

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


"But this also refreshes the page"
Not sure about Vue2 but works like a charm in Vue3 (without page-refresh)
A
Andre M

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.


C
ChiKa LiO

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


p
parker_codes

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

How do you access this.$route.query in vue3 composition API ?
d
double-beep
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })

I liked this answer the best. Unfortunately this causes Error: Avoided redundant navigation to current location
Fix: this.$router.push({ query: Object.assign({...this.$route.query}, { new: 'param' }) })
But now that I think about it you can just do this.$router.push({ query: {...this.$route.query,new: 'param'},) })
How do you access this.$route.query in vue3 composition API ?
@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 });
h
hayumi kuran

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' }),
      },
      () => {}
    )

This causes page to scroll to top.
B
Boris

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

L
Ludolfyn

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.


second argument should be a string, so window.history.replaceState(null, '', '?query=myquery');
v
vir us

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)
    },

m
mostafa

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

Example:

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

S
Sachin S

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

Z
Zakirsoft

With RouterLink

//With RouterLink Route Text //With Methods methods(){ this.$router.push({name:'route-name', params:{paramName: paramValue}}) }

With Methods

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

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.