Nuxt3 Router – $route is not defined

I’ve set up a fresh Nuxt3 project, and am having an issue when I use a NuxtLink component to navigate to a dynamic route page.

<template>
  <div>
    <div v-for="project in projects.projects">
        <NuxtLink :to="{ path: `/projects/${project.id}` }">{{project.text}}</NuxtLink>
    </div>
    <button @click="projects.addProject('Test Project', 'Director')">Add Project</button>
    </div>
</template>

<script>
import { useProjectsStore } from '@/store/projects.js'
export default {
  setup() {
    const projects = useProjectsStore()

    return { projects }
  },
}
</script>

In this code here, when I click add project, it creates a NuxtLink component fine. When I click the link, the URL changes in the window to /projects/0 as expected, but I get this error in the console and the page content doesn’t update.

Uncaught (in promise) ReferenceError: $route is not defined at [id].vue:14:72

But when I refresh the page, going directly to the /projects/0 location, it loads fine with no $route is not defined error.

Weirdly though, if I add in a NuxtLink component that goes to /projects/0 and click that link, instead of creating the NuxtLink component with the Add Project button, the route works fine with no error.

This is the [id].vue file contents:

<template>
  <div>
      <h2>Single project</h2>
    <h1>{{project}}</h1>
  </div>
</template>

<script>
import { useProjectsStore } from '@/store/projects.js'

export default {
  setup() {
    const projects = useProjectsStore()
    const project = projects.projects.find((project) => project.id === $route.params.id)

console.log(project);
    return { project }
  },
}

</script>

>Solution :

You should use the composable function useRoute to get the route instance in the setup hook :

export default {
  setup() {
    const projects = useProjectsStore()
    const route=useRoute()
    const project = projects.projects.find((project) => project.id === route.params.id)

console.log(project);
    return { project }
  },
}


Leave a Reply