close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to set URL query params in Vue with Vue-Router in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

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

  1. How to set URL query params in Vue with Vue-Router ?

    to set URL query params in Vue with Vue-Router 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 });

  2. How to set URL query params in Vue with Vue-Router ?

    to set URL query params in Vue with Vue-Router 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 });

Method 1

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.

Method 2

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

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment