You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router实现子页面刷新时重定向至网站根目录的方法

实现刷新特定子页面重定向到根目录的方案

方案一:全局前置路由守卫(推荐)

在路由配置文件(如router/index.ts)中添加全局守卫,统一拦截刷新进入的指定页面,直接重定向到根目录。

import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';

// 你的原有路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: HeaderLayout,
    children: [
      { path: '', component: FacilitiesPage, name: 'facilities' },
      { path: '/dashboard/:facId', component: DashboardPage, name: 'dashboard' },
      { path: '/settings', component: SettingsPage, name: 'settings' },
      { path: '/remote-control/:facId', component: RemoteControlPage, name: 'remote-control' },
    ],
  },
  {
    path: '/login',
    component: PlainLayout,
    children: [{ path: '', component: LoginPage, name: 'login' }],
  },
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 添加全局前置守卫
router.beforeEach((to, from) => {
  // 定义需要拦截刷新的路由名称
  const needRedirectRoutes = ['dashboard', 'remote-control'];
  
  // 刷新页面时from.name为undefined,且目标路由在拦截列表中
  if (!from.name && needRedirectRoutes.includes(to.name as string)) {
    return { name: 'facilities' }; // 重定向到根目录对应的路由
  }
});

export default router;

逻辑说明:用户刷新页面时,from对象的name属性为空(非路由跳转触发的页面加载),此时若目标路由是指定的子页面,就强制跳转到根路由的首页。

方案二:单个页面组件内处理

如果只需要针对个别页面,可在对应组件的created钩子中判断是否为刷新进入,然后执行重定向。

以DashboardPage.vue为例:

<script setup lang="ts">
import { useRouter } from 'vue-router';

const router = useRouter();

// performance.navigation.type === 1 表示当前页面是刷新进入
if (performance.navigation.type === 1) {
  router.push({ name: 'facilities' });
}
</script>

将相同逻辑复制到RemoteControlPage.vue即可,这种方式适合只需要处理少数页面的场景。

注意事项

  • 若后续需要新增拦截页面,只需在needRedirectRoutes数组中添加对应路由名称即可。
  • 全局守卫方案不受keep-alive缓存影响,更适合全局统一管理的场景。

内容的提问来源于stack exchange,提问作者f_up

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:22:19