Using URL Query Params in Nuxt 3

Using URL Query Params in Nuxt 3

Using URL Query Params in Nuxt 3

This is a continuation of my previous post on how to set query parameters in Nuxt 3. We'll be continuing with the code written there so make sure you check it out.

The problem we're solving

We left off with our URL looking like localhost:3000/test?streamer=faker. This is nice but contained a few cases that are less than ideal.

Because the URL parameter is being updated using our input's v-model, if the page is refreshed, we lose that local state and the value stored in twitchStreamer.

Using useRoute in Nuxt

NuxtJS relies on vue-router for most of its routing logic.

In our example, we are using the Composition API, one of the new features built into Nuxt 3.

In order to get our route, we use bring useRoute() into our setup(). Nuxt 3 auto-imports useRoute() so we can chose to be explicit or implicit.

setup() {
  const route = useRoute()
}

Having our route unlocks all of the benefits of vue-router, including access to our query params!

Making the query param persist

With access to our route, we can check the query variable (what's after the = in streamer=) using route.query.streamer.

Easy!

I now use this logic alongside a ternary operator with the twitchStreamer variable.

const twitchStreamer = ref(route.query.streamer ? route.query.streamer : '')

Now, every time the page is navigated to or refreshed, our twitchStreamer will check if our route has a streamer query parameter.

If it does, our twitchStreamer will contain the parameter's value. Otherwise, it'll be an empty string.

Final code snippet

<!-- pages/example.vue -->
<template>
  <input v-model="twitchStreamer" />
</template>

<script>
  setup() {
    const route = useRoute()
    const router = useRouter()
    const twitchStreamer = ref(route.query.streamer ? route.query.streamer : '')

    watch(twitchStreamer, (twitchStreamer, previous) => {
      router.push({
        path: '/test',
        query: { streamer: twitchStreamer },
      })
    })

    return { twitchStreamer }
</script>