javascript - 配置 router.beforeEach
问题描述
当他(它)单击箭头返回浏览器的上一页时,我尝试在主页上取回用户。
当我在页面登录时,我无法使用浏览器的箭头返回。
我们建议我使用“路由 BeforeEach”我不明白它是如何工作的。
主.js:
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/login',
name: 'Login',
component: Login,
meta: { requiresAuth: true }
},
{
path: '/register',
name: 'Register',
component: Register,
},
{
path: '/complete_registration',
name: 'Complete Registration',
component: CompleteRegistration,
},
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: { requiresAuth: true }
}
]
const router = new VueRouter({routes, mode: 'history'})
router.beforeEach((to, from, next) => {
if ( from.matched.some(record => record.meta.requiresAuth) ) {
alert('enter')
next('/');
} else {
next();
}
});
通过连接我,它会在警报的循环弹出窗口中显示我
解决方案
Thomas Kleßen 的评论完全正确:
- 您应该
meta: { requiresAuth: true }
只添加到需要对用户进行身份验证的路由。登录页面不是这种情况(我猜也不是注册和主页)。 - 您应该检查“目标”
router.beforeEach()
是否需要对用户进行身份验证,即to
(而不是与from
您来自的页面相对应的 )。
但是,您需要添加额外的检查:如果用户未通过身份验证,您需要将她/他重定向到登录页面。为此,您可以使用firebase.auth().currentUser
,如下所示。请在此处查看相应的 Firebase 文档。
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
},
{
path: '/complete_registration',
name: 'Complete Registration',
component: CompleteRegistration
},
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: { requiresAuth: true }
},
{
path: '/otherProtectedPage',
name: 'OtherProtectedPage',
component: OtherProtectedPage,
meta: { requiresAuth: true }
}
]
const router = new VueRouter({routes, mode: 'history'})
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const currentUser = firebase.auth().currentUser
if (requiresAuth && !currentUser) {
next('/login')
} else if (requiresAuth && currentUser) {
next()
} else {
next()
}
})
推荐阅读
- c# - 使用 unmamagedexports 从 Access VBA 调用 C# DLL 时出现 VBA 错误 49 和错误 424
- laravel - 如何在有作业运行时将 laravel 部署到 docker 容器中
- java - 使用数据库实现 Rest 测试
- performance - Kotlin 中的 get 和 [] 有什么区别?
- django - Django:每小时重置模型的特定字段
- java - 拒绝访问从 firebase 检索数据
- vuejs2 - Vue.js 3.2.1 下 Gauge.js 组件未创建
- sql-server - 用于转置的重复案例函数
- typescript - 如何键入检查内存中的 TypeScript 代码片段?
- python - 如何使用 UDP 和 Asyncio 进行从服务器到客户端的多个文件传输 - python