Preface
The useRouter must be placed at the top level in the setup method, otherwise the scope changes useRouter() returns undefined.
Use correctly
<script setup> import { useRouter } from 'vue-router'; const router = useRouter(); const toLogin = () => { ({ name: 'login' }); }; </script>
Incorrect use
<script setup> import { useRouter } from 'vue-router'; const toLogin = () => { const router = useRouter(); //router is undefined ({ name: 'login' }); }; </script>
If you need to use routing objects in non-setups of other js files, you can directly refer to the routing object created by createRouter().
Summarize
This is the article about the problem of undefined after the return value of useRouter() is executed. For more related content, please search for my previous article or continue to browse the related articles below. I hope everyone will support me in the future!