SoFunction
Updated on 2025-04-07

vue3 solution to report error using useRouter in custom hooks

Use useRouter in custom hooks to report an error

With the update of vue3, vue-router has also been updated

useRouter

This.$router global routing instance equivalent to vue2 is an instance of router constructor

useRoute

This.$route, equivalent to vue2, represents the status information of the currently activated route, contains the information obtained from the current URL resolution, and the route routing record that the URL matches.

But found in one use

import { useRoute, useRouter } from "vue-router"

useRoute, useRouter must be written into the setup, see for detailsvue-next-router.Forcibly use these two reports undefined in the function, resulting in the inability to obtain routing data and routing methods.

So what should I do if I want to use routing in custom hooks?

After exploration, you can directly introduce routing objects from the route

// import { useRoute, useRouter } from "vue-router"
import Vrouter from "@/router"
 
// const router = useRouter();
// const route = useRoute();
 
const route = 
const router = Vrouter

Monitoring the current route is the same

eg:

watch(() => ,
    (query) => {
       = (params,query)
       = handleParams()
    })

Note: Never monitor the entire router object directly.

Use() to report an error "Cannot read property 'use' of undefined"

Problem: When learning Vue 3, I found that the following code reported an error

The error message is: Cannot read property 'use' of undefined

import Vue from 'vue'
import router from './router'
(router)

reason

() is the way to install plug-ins in Vue 2

In Vue 3, import Vue from 'vue' cannot export the "vue" package

Vue 3 uses createApp(App) to return the application instance

Correct solution

import { createApp } from 'vue'
import App from './'
import router from './router'
createApp(App).use(router).mount('#app')

The above is personal experience. I hope you can give you a reference and I hope you can support me more.