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>