Web development and Tech news Blog site. WEBISFREE.com

HOME > nuxtjs

How to change the query string using useRouter in NuxtJS

Last Modified : 04 Mar, 2023 / Created : 04 Mar, 2023
636
View Count


If you use NuxtJS, you can learn how to use the useRouter hook to change the query string. For example, the query string in the address bar will only be changed as follows.

Before) https://webisfree.com/?category=vuejs
After) https://webisfree.com/?category=nuxtjs



By the way, when it is necessary to change the query string, it can be used to implement the function of passing specific information (such as category or current page) on a page. For example, when you revisit or refresh a page, you can show different information depending on the query string. If this method is not used, you may need to use local storage methods such as cookies or local storage.



# Using NuxtJS useRouter to modify querystring.


First, let's see how to change the query string. Please take a look at the following code.
import { useRouter } from 'nuxt'

const myComponent = () => {
  const router = useRouter()
  const updateQueryStr = () => {
    router.push({
      query: { category: 'nuxtjs' }
    })
  }

  return (
     <button onClick={updateQueryStr}>Update a category</button>
  )
}

In the above example, there is one button which serves as a button to change the category. When clicked, it runs the updateQueryStr() function using the useRouter hook, which performs the simple task of changing the current query string category value to nuxtjs.

Let's take a closer look at the router.push() part. Generally, it is commonly used to navigate pages using either the path or name property, like the following.
router.push({
  path: '/',
  query: { category: 'nuxtjs' }
})

However, if you only use queries like this, you can change the query string without moving the page. That means you can use it without using push or name if you don't need to move the page.
router.push({
  query: { category: 'nuxtjs' }
})


So far, we have learned how to easily change the query string in Nuxt.js using useRouter().
Perhaps you're looking for the following text as well?

    Previous

    [NuxtJS] Creating NuxtJS 404 or 500 error pages

    Previous

    [nuxtjs] How to Easily and Quickly Create a Sitemap Using @nuxtjs/sitemap