Leveraging the useRoute() function with Vue 3 Composition API and Typescript: [Vue alert]: The injection "Symbol(route location)" was not detected when employing Typescript

Just recently, I upgraded a Vue 2 application that heavily uses Vue Router and TypeScript to Vue 3. During the migration process, I switched a function from reading the route using this.$route in the Options API to using useRoute() in the Composition API. However, after making this change, the component failed to load with the following error:

[Vue warn]: injection "Symbol(route location)" not found. 
  at <Content pageName="homepage" onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< viewRef > > 
  at <RouterView> 
  at <Website>

To make troubleshooting easier, I have minimized the app as much as possible and here is the set up where the error occurs:

The dependencies I am working with are: "vue": "^3.3.4", "vue-router": "^4.2.1",

This is the entry point code:

website.js
import { createApp } from "vue"
import router from "./routes/router.js"
import Website from "./website.vue"
const app = createApp(Website)
app.use(router)
app.mount("#shop")

Now, let's take a look at the base component:

website.vue
<template lang="pug">
router-view
</template>

<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
    name: "Website"
})

Next, the router configuration:

router.js
import { createRouter, createWebHistory } from "vue-router"
import Content from "../components/content.vue"

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/",
            components: {
                default: Content,
                },
            props: {
                default: { pageName: "homepage" }
            },
    ]
})

export default router

Now, let's examine the active component that previously worked with the Options API:

content.vue
<template lang="pug">
h1 {{ myroute.fullPath }}
</template>

<script>
export default {
    name: "Content",
    props: {
        pageName: { 
            type: String,
            required: true
        }
    },
    computed: {
        myroute() {
            return this.$route
        }   
    }
}
</script>

When using the Composition API, the component looks like this:

content.vue
<template lang="pug">
h1 {{ myroute.fullPath }}
</template>

<script>
import { useRoute } from "vue-router"

export default {
    name: "Content",
    props: {
        pageName: { 
            type: String,
            required: true
        }
    },
    setup(props) {
        const route = useRoute()
        return {
            myroute: route
        }
    }
}
</script>

However, when switching to TypeScript implementation like this:

content.vue
<template lang="pug">
h1 {{ myroute.fullPath }}
</template>

<script lang="ts>
import { useRoute } from "vue-router"
import { defineComponent } from "vue"

export default defineComponent ({
    name: "Content",
    props: {
        pageName: { 
            type: String,
            required: true
        }
    },
    setup(props) {
        const route = useRoute()
        return {
            myroute: route
        }
    }
})
</script>

An unexpected warning pops up:

[Vue warn]: injection "Symbol(route location)" not found. 
  at <Content pageName="homepage" onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <Website>

And an accompanying error message reads:

Uncaught (in promise) TypeError: can't access property "fullPath", $setup.myroute is undefined

It seems puzzling how simply transitioning to TypeScript could lead to broken functionality in the code.

Answer №1

Dealing with a comparable problem recently, I found that adjusting my tsconfig modules from

"module": "commonjs",
to
"module": "esnext"
was the solution. Hopefully, this tip proves helpful for you as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Despite attempts to exclude them, types in node_modules continue to be compiled in TypeScript

During my attempt to compile my typescript source code, I've noticed that the compiler is also attempting to compile the types found within my node_modules directory. I am currently utilizing typescript version 2.6.1 and have my tsconfig file set up ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

How to remove an event listener when e.target points to a hyperlink

element, I encountered an issue using a slideshow component sourced from our components library. This component receives swipe events from a utility function that is initialized upon mounting. The problem arose while testing on a mobile phone - tapping a ...

Incorporating trail markers in your Vue.js app

Currently I'm working on implementing breadcrumbs for my Vue.js application. I am using a store component where I can access the current value and back state, but I am struggling to determine how to obtain the path between pages for the breadcrumbs. M ...

How to dynamically bind items in vuejs

I have a basic select that I would like to bind to an array. My framework is Vuetify, but this issue is common across platforms. <v-select v-bind:items="physicianListSpeciality" > </v-select> Now I want to use the same select for multiple arr ...

Is your Typescript struggling to infer types correctly?

I created a function that converts an Array into a Map: function toMap<T,TKey,TElement>(items: Array<T>, keySelector: (item: T) => TKey, elementSelector: (item: T) => TElement ): Map<TKey,TElement> { var ma ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

Trigger function when the element is generated

Is there a way to execute a function only once while still having it run each time a new element is created using v-for? <div v-for"value in values"> <div @ function(value, domElement) if value.bool===true @> </div> ...

Testing Angular components using mock HTML Document functionality is an important step in

Looking for help on testing a method in my component.ts. Here's the method: print(i) { (document.getElementById("iframe0) as any).contentWindow.print(); } I'm unsure how to mock an HTML document with an iframe in order to test this meth ...

Encountering a TypeError when using Webpack and ts-loader to bundle a third-party library

While everything compiles and bundles successfully, a TypeError is encountered in the browser: "box2dweb_commonjs_1.default is undefined." No errors occur when starting webpack-dev-server and reviewing the bundle at http://localhost:8080/webpack-dev-serv ...

What is the use of the typeof operator for arrays of objects in TypeScript?

How can I update the any with the shape of the options's object below? interface selectComponentProps { options: { label: string; value: string; }[]; } const SelectComponent: React.FC<selectComponentProps> = ({ options, }) => ...

Integrating a Vue application with an OpenId provider using the OpenId Connect library

Currently, I am in the process of developing a Single Page Application with Vue on the client-side and Java Spring REST APIs on the backend. My goal is to add security measures using OpenId Connect, specifically with RapidIdentity as the provider. Unlike ...

The nest build process encounters errors related to TypeScript in the @nestjs/config package, causing it

Encountering several issues related to @nestjs/config, causing the npm build command to fail. However, npm run start:dev is still functional despite displaying errors. See below for screenshots of the errors and environment: ...

Using alternate variables in the watchQuery() function in Apollo Angular will generate the cached data

Currently, I am implementing a feature in my project that allows users to access and analyze data based on various parameters such as year, location, and gender. Below is the code snippet that I have developed for this feature: this._querySubscription = ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

The system encountered an issue regarding a missing dependency: Warning from chokidar (C:): Error: EBUSY: resource busy or locked, unable to access 'C:hiberfil.sys'

While working with Vue, I encountered an error after running npm run serve. Here is the screenshot of the error: Does anyone have suggestions on how to resolve this issue? ...

Using vue.js to make an HTTP GET request to a web API URL and display

I am currently utilizing vue.js to make an http request to a web api in order to retrieve a list of projects and display them in a list. However, I am encountering an issue where only one item from the response array of eight items is being rendered. Any a ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...

Explain a TypeScript function that takes an object as input and returns a new object with only the

Check Playground What's the best way to define a type for this specific function? The inputObject should contain all keys from the enablePropertiesArray and may have additional ones. The function is expected to return a copy of the inputObject, inclu ...