vue-router: useRouter() return undefined
when i use useRouter break away vue hooks , it return undefined, but in the vue hooks, it return Router.
so i dont know this reason, Please answer me how to use useRouter is normal js, because i want to use it in vuex

About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 2
- Comments: 16
useRouter must be called inside of setup() (documentation link)
But you can use composition api for extract logic of routing
I hope it helps, good luck!
you can import you created router to use in any files,
For example:
or use
window.location.hrefuseRouter()was returning undefined for me in my own composable, though. I’ll have to double-check the stack again to make sure it’s originating from a<script setup>.If I only able to use it in setup script, how do I redirect route in axios interceptor file then?
Welp, this is what comes up on Google when you search the issue.
@chris-zhu Did you figure this out?
Hello, thank you for taking time filling this issue!
However, we kindly ask you to use our Issue Helper when creating new issues, in order to ensure every issue provides the necessary information for us to investigate. This explains why your issue has been automatically closed by me (your robot friend!).
I hope to see your helper-created issue very soon!
just got hit by this issue, sometimes
useRouter()returned undefined.Another option is to use a dynamic import:
This is not the first time I have faced this problem, I think I have finally grown up to have the ability to solve it. The correct solution is to cache the call results during setup.
You can try using the following code for inspiration
This behavior, which can only be called during setup initialization, is like a joke that will severely hit beginners. To be honest I think it’s best for the document to provide a detailed explanation of this situation, rather than being confusing https://router.vuejs.org/api/#useRoute:~:text=RouteLocationNormalizedLoaded-,useRouter,Router,-FREE WEEKEND
Examples of mistakes that many people make
Sorry. Do you have any solutions on that?
Add useRouter change onMounted to async add await router.isReady() before setting parameters
What if I have a composable that needs to reference another composable? E.g. my composable needs to use
useRouterto grab the route? I suppose I have to use dependency injection?