Vue3 script setup中如何在App.vue获取当前路由名称?
解决Vue3 App.vue中onMounted获取路由名称异常的问题
问题核心是onMounted钩子执行时,Vue Router的初始导航还未完成,这时拿到的是初始路由状态(比如默认的"/"),而模板里的路由值是响应式的,会在路由导航完成后自动更新,所以能显示正确的路由名称。
有两种可靠的解决方式:
方式一:监听路由变化
通过watch监听route对象,每次路由切换时自动执行判断逻辑,确保总能拿到最新的路由状态:
<script setup> import { RouterView, useRouter, useRoute } from "vue-router"; import Navigation from "./components/Navigation.vue"; import Footer from "./components/Footer.vue"; import { ref, watch } from "vue"; const navigationDisabled = ref(false); const route = useRoute(); const checkRoute = () => { const excludeRoutes = ["login", "register", "forgot-password"]; navigationDisabled.value = excludeRoutes.includes(route.name); }; // 监听路由变化,实时更新状态,immediate确保初始化时执行一次 watch(route, checkRoute, { immediate: true }); </script>
方式二:等待路由初始化完成
利用router.isReady()方法,它会返回一个Promise,在初始路由导航完成后才会resolve,确保拿到最终的路由状态;同时监听后续路由切换,覆盖所有场景:
<script setup> import { RouterView, useRouter, useRoute } from "vue-router"; import Navigation from "./components/Navigation.vue"; import Footer from "./components/Footer.vue"; import { onMounted, ref } from "vue"; const navigationDisabled = ref(false); const router = useRouter(); const route = useRoute(); const checkRoute = () => { const excludeRoutes = ["login", "register", "forgot-password"]; navigationDisabled.value = excludeRoutes.includes(route.name); }; onMounted(async () => { // 等待初始路由导航完成 await router.isReady(); checkRoute(); }); // 监听后续路由切换 router.afterEach(checkRoute); </script>
另外注意:原代码中navigationDisabled的初始值建议设为false而非null,逻辑会更严谨。
内容的提问来源于stack exchange,提问作者Kenta
相关产品推荐
相关产品推荐

