你可以使用 Vue 路由的守卫来完成这个功能。
首先,你需要在路由配置中为每个需要验证登录的路由设置一个路由守卫。这个守卫函数会在路由跳转之前运行,你可以在函数中检查用户是否已经登录,如果没有登录,就可以跳转到登录页面,或者终止路由跳转。
示例代码:
const routes = [
{
path: '/private',
component: PrivatePage,
beforeEnter: (to, from, next) => {
if (isLoggedIn()) {
next(); // 已登录,继续跳转
} else {
next('/login'); // 未登录,跳转到登录页
}
}
}
];
const router = new VueRouter({ routes });