Vue Router: Uncaught (in promise) Error: Navigation cancelled

解决编程式路由往同一地址跳转时会报错的情况

Uncaught (in promise) Error: Navigation cancelled from "xxx" to "xxx" with a new navigation.在这里插入图片描述

解决:在router文件夹下等index.js文件中写入

// router文件夹下等index.js文件中写入
//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
//push
VueRouter.prototype
import { createRouter, createWebHistory } from 'vue-router' // 路由白名单(不需要鉴权的路径) const WHITE_LIST = ['/login', '/404'] // 动态导入组件(增加加载状态处理) const lazyLoad = (path) => () => import(/* webpackChunkName: "[request]" */ `@/views/${path}/index.vue`) // 路由配置 const routes = [ { path: '/', name: 'index', component: lazyLoad('index'), meta: { title: '首页', requiresAuth: true // 需要登录鉴权 } }, { path: '/login', name: 'login', component: lazyLoad('login'), meta: { title: '登录', guestOnly: true // 仅允许未登录用户访问 } }, { path: '/:catchAll(.*)', // 404处理 name: 'not-found', component: lazyLoad('404'), meta: { title: '页面不存在' } } ] const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes }) // 路由鉴权逻辑 router.beforeEach(async (to, from, next) => { // 设置页面标题 document.title = to.meta.title || '默认标题' const isAuthenticated = checkAuthStatus() // 获取当前登录状态 // 在白名单中直接放行 if (WHITE_LIST.includes(to.path)) return next() // 需要登录但未认证 if (to.meta.requiresAuth && !isAuthenticated) { next({ path: '/login', query: { redirect: to.fullPath } // 携带重定向地址 }) } // 已登录用户访问guestOnly页面 else if (to.meta.guestOnly && isAuthenticated) { next(from.path === '/login' ? '/' : from) // 避免登录后无限循环 } // 正常放行 else { next() } }) // 检查认证状态的方法(根据实际业务实现) function checkAuthStatus() { return localStorage.getItem('token') !== null } export default router 为什么我使用router.push('/')方法没反应
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值