gpt4 book ai didi

browser - Vue-router,如何防止用户在浏览器中按下后退按钮返回登录屏幕?

转载 作者:搜寻专家 更新时间:2023-10-30 22:33:37 25 4
gpt4 key购买 nike

这段代码通过修改url防止用户返回登录界面,但是如果他们点击浏览器中的后退按钮,即使登录了也可以回到登录界面。

用户数据在用户身份验证时保存在localstorage'info'中,当它退出时localstorage更新为null

router.beforeEach((to, from, next) => {
if(window.localStorage.getItem('info') !== null && to.path == '/login'){
next(from.fullPath)
}
if(window.localStorage.getItem('info') === null && to.path != '/login'){
next('/login')
}
next()
})

请帮帮我!

最佳答案

可以使用 navigation guardsroute meta fields ,它允许将特定于路由的规则委托(delegate)给路由器文件。

beforeEach 代码(例如在 main 文件中):

// Check the user's status, and route rules
router.beforeEach((to, from, next) => {
// Redirect if user is disallowed to view the page
const isLogged = !! store.getters.getUser
if (isLogged && to.meta.disallowAuthed) {
return router.push('/my-redirect-page')
}

return next()
})

路由定义(设置元标志disallowAuthed):

login: {
path: '/login',
name: 'login',
component: TheLoginPage,
meta: { disallowAuthed: true }
},

注意事项

元字段从父路由传播到子路由 - 如果还需要检查路由的父 meta 字段,请使用此(检查两个所选路由的元和任何父级别的路由元数据):

const isDisallowAuthed = to.matched.some((route) => route.meta.disallowAuthed)

而不是直接访问它:

const isDisallowAuthed = to.meta.disallowAuthed

恕我直言,在处理身份验证逻辑时最好采用这种方法,因为直接检查 meta.flag 需要在重构路由文件时记住这个警告的心理开销。

相关问题:https://github.com/vuejs/vue-router/issues/704

关于browser - Vue-router,如何防止用户在浏览器中按下后退按钮返回登录屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50087164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com