vue3中useRouter()执行后返回值是undefined问题

发布于:2023-04-01 ⋅ 阅读:(700) ⋅ 点赞:(0)

useRouter一定要放在setup方法内的顶层,否则作用域改变useRouter()执行返回的是undefined。

正确使用

<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const toLogin = () => {
    router.push({ name: 'login' });
};
</script>

错误使用

<script setup>
import { useRouter } from 'vue-router';
const toLogin = () => {
    const router = useRouter(); //router为 undefine
    router.push({ name: 'login' });
};
</script>