nuxt3.jsnuxt-link

How to use NuxtLink without writing query every time?


I have a problem with Nuxt 3. Here is the code:

<NuxtLink
:to="{
  path: '/',
  query: useRoute().query,
}">Link</NuxtLink>

How to use this code without writing query, like the code below, but without losing parameters? If I'm not writing query, it's making the URL query parameters empty but redirecting to needed page:

<NuxtLink to="/">Link</NuxtLink>

Thank you!


Solution

  • You can try a custom function to unify your to object. This gives you some degree of flexibility in the template in case you need to manipulate the to object

    // ~/helpers.js
    
    const { query } = useRoute()
    const pathWithQuery = (path) => {
      return {
        path,
        query
      }
    }
    export {
      pathWithQuery
    }
    
    // ~/pages/index.vue
    // or your page template
    
    <script setup>
    import { pathWithQuery } from '~/utils/helpers'
    </script>
    <template>
      <NuxtLink :to="pathWithQuery('/')">Link</NuxtLink>
      <NuxtLink :to="pathWithQuery('/page-2')">Link 2</NuxtLink>
      <NuxtLink :to="{ path: '/page-3', query: { foo: 'one-off-value' } ">Link 3</NuxtLink>
      <NuxtLink :to="pathWithQuery('/page-4')">Link 4</NuxtLink>
    </template>
    

    Alternatively, if you want a more global override, you can create a global route middleware that adds a query from the current route object to the next one, if no query is found. You can then use <NuxtLink> as usual

    https://nuxt.com/docs/migration/plugins-and-middleware#route-middleware https://nuxt.com/docs/guide/directory-structure/middleware

    // ~/middleware/query-override.js
    
    export default defineNuxtRouteMiddleware((to, from) => {
      if (!to.params.query) {
        // if no query is specified
        return navigateTo({
          path: to.path, // navigate to the designated path
          query: from.query // and add the query from the previous route
        })
      }
    })
    
    // ~/pages/index.vue
    // or your page template
    
    <template>
      <NuxtLink to="/">Link</NuxtLink>
      <NuxtLink to="/page-2">Link 2</NuxtLink>
      <NuxtLink :to="{ path: '/page-3', query: { foo: 'one-off-value' } ">Link 3</NuxtLink>
      <NuxtLink to="/page-4">Link 4</NuxtLink>
    </template>