SoFunction
Updated on 2025-04-06

The problem of undefined after the return value in useRouter is solved

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

&lt;script setup&gt;
import { useRouter } from 'vue-router';
const toLogin = () =&gt; {
	const router = useRouter(); //router is undefined    ({ name: 'login' });
};
&lt;/script&gt;

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!