Vue Router定义全局前置守卫 官网
在Vue Router里,全局前置守卫可在路由切换前执行检查。全局前置守卫用router.beforeEach定义,它接收一个回调函数,该函数有to、from和next三个参数。to是要去的路由,from是当前路由,next用于决定是否继续导航。 // 定义全局前置守卫const router = new VueRouter({ routes: [...] });router.beforeEach((to, from, next) => { // 检查是否登录 const isLoggedIn = false; if (to.path === '/dashboard' !isLoggedIn) { next('/login'); // 未登录,跳转到登录页 } else { next(); // 继续导航 }}); 注意:next函数必须调用,不然导航会被挂起。