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

Vue Router页面刷新后无法停留在当前页面问题求助

Vue 3 + Vue Router 4 + Vite 5 刷新页面自动重定向至根路径问题

环境

  • Vue ^3.4.21
  • vue-router ^4.3.0
  • Vite ^5.2.8

问题

在/someanotherpath页面按F5刷新后,页面未停留在当前路径,而是自动重定向至/。

已尝试的解决方法

  • 移除router.beforeEach路由守卫,问题依旧存在
  • 给<router-view>添加:key="route.fullPath"属性,无效

相关代码

路由文件代码

import { createRouter, createWebHistory } from "vue-router";
import { jwtDecode } from "jwt-decode";
import Home from "@/views/login/Login.vue";
import PasswordRecovery from "@/views/login/PasswordRecovery.vue";

const routes = [
    {
        path: "/",
        component: Home,
        name: "home",
        meta: { displayName: "home", icon: "home", authRequired: true },
    },
    {
        path: "/someanotherpath",
        component: PasswordRecovery,
        name: "someanotherpath",
        meta: { displayName: "", authRequired: false },
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    if (to.matched.some((record) => record.meta.authRequired)) {
        const token = localStorage.getItem("token");

        if (token) {
            try {
                const decoded = jwtDecode(token);

                if (decoded.exp && decoded?.exp > Date.now() / 1000) {
                    next();
                } else {
                    localStorage.clear();
                    if (
                        to.path !== "/login" &&
                        to.name !== "password-recovery"
                    ) {
                        next("/login");
                    } else {
                        next();
                    }
                }
            } catch (e) {
                console.error(e);

                localStorage.clear();
                if (to.path !== "/login" && to.name !== "password-recovery") {
                    next("/login");
                } else {
                    next();
                }
            }
        } else {
            if (to.path !== "/login" && to.name !== "password-recovery") {
                next("/login");
            } else {
                next();
            }
        }
    } else {
        next();
    }
});

export default router;

Vite 配置文件代码

import { defineConfig } from "vite";
import { fileURLToPath, URL } from "url";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: [
            {
                find: "@",
                replacement: fileURLToPath(new URL("./src", import.meta.url)),
            },
            {
                find: "@assets",
                replacement: fileURLToPath(
                    new URL("./src/shared/assets", import.meta.url)
                ),
            },
            {
                find: "@cmp",
                replacement: fileURLToPath(
                    new URL("./src/shared/cmp", import.meta.url)
                ),
            },
            {
                find: "@stores",
                replacement: fileURLToPath(
                    new URL("./src/shared/stores", import.meta.url)
                ),
            },
            {
                find: "@use",
                replacement: fileURLToPath(
                    new URL("./src/shared/use", import.meta.url)
                ),
            },
        ],
    },
    build: {
        sourcemap: true,
    },
});

问题分析与解决方案

1. 排查组件内部的自动跳转逻辑

移除路由守卫后问题仍存在,说明重定向并非由路由守卫触发。重点检查PasswordRecovery组件(对应/someanotherpath)和Login.vue(对应/)的生命周期钩子(如created、mounted)中是否存在判断token后自动跳转至/的代码,例如:

// 示例可能存在的错误代码
if (localStorage.getItem('token')) {
  this.$router.push('/')
}

如果存在此类代码,需根据业务需求调整逻辑(比如仅在已登录用户进入登录页时跳转,而非密码找回页)。

2. 修正路由守卫中的路径错误

路由代码中多次出现跳转到/login的逻辑,但路由配置里并没有/login路径,登录页对应的是根路径/。这个错误会导致路由跳转至不存在的路径,可能触发默认重定向行为。需将所有next("/login")改为next("/"),同时将判断条件to.path !== "/login"改为to.path !== "/";另外路由中/someanotherpath的name是someanotherpath,但路由守卫中判断的是to.name !== "password-recovery",名称不匹配的问题也需同步修正:

// 修正后的路由守卫片段
if (decoded.exp && decoded?.exp > Date.now() / 1000) {
    next();
} else {
    localStorage.clear();
    if (
        to.path !== "/" &&
        to.name !== "someanotherpath"
    ) {
        next("/");
    } else {
        next();
    }
}

3. 确认Vite开发服务器的SPA配置

虽然Vite默认支持SPA的history模式,但可显式添加historyApiFallback配置确保所有路由请求都指向index.html,避免刷新时出现404后被服务器重定向:

// vite.config.ts 中添加server配置
export default defineConfig({
    // ...其他配置
    server: {
        historyApiFallback: true
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:45:55