繁体   English   中英

页面刷新时 Vue Router Gaurd 不工作

[英]Vue Router Gaurd Not Working When Page Refreshes

我正在尝试使用路由器保护来保护某些页面。 当用户访问时,他们应该在尝试访问这些页面时被要求登录。 当我在应用程序中时它可以工作,但是当用户刷新页面,或者只是简单地复制 URL 并将其粘贴到浏览器上并在那里登录时,用户应该仍然可以获得这些页面。 但现在情况并非如此。 它会抛出此错误:[vue-router] 路由导航期间未捕获的错误:如果用户尝试访问受保护的页面,我需要将用户重定向到登录页面,并且如果他们已登录,还给他们这个页面。

beforeEnter: (to, from, next) => {
    if (!store.state.isUserLoggedIn) {
    next({
    path: '/login', // back to safety
    query: {
    redirectFrom: to.fullPath
    }
    })
    // }else if(!localStorage.getItem('userLoggedIn')){
    // next()
     } else {
    next()

最佳实践以及您应该在这里做的是使用Navigation Guards

index.js(路由器文件)

const ifNotAuthenticated = (to, from, next) => {
    if (!store.state. isUserLoggedIn) {
        next();
        return;
    }
    next("/");
};

const ifAuthenticated = (to, from, next) => {
    if (store.state. isUserLoggedIn) {
        next();
        return;
    }
    next("/login");
};

const routes =[
    {
        path: "/home",
        name: "Home",
        component: Home,
        beforeEnter: ifAuthenticated,
      },
    {
        path: "/login",
        name: "Login",
        component: Login,
        beforeEnter: ifNotAuthenticated,
      }
]

beforeEnter这里是了解经过身份验证的用户是否应该进入下一页或 go 登录的关键。

在仔细研究了我遇到的错误之后,我意识到当页面刷新或用户直接导航到 URL 时,路由器防护甚至没有看到持久的 Vuex state。 所以我决定切换路由器守卫分析的变量,以查看用户是否登录到 localStorage 变量。 即便如此,当它是 boolean 变量时,我也遇到了问题。 我将其更改为 int,1 表示已登录的 state,0 表示已注销的 state。 这完美无缺。 以防万一有人遇到这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM