首页 > 解决方案 > 必须点击登录按钮两次;使用 vue-router 和 firebase 身份验证

问题描述

我已经设置了一个路由器保护,所以当我登录而不是我的路由器第二次将它推送到仪表板时,它需要 firebase 进行身份验证,它认为我没有登录,我必须等待并再次单击登录按钮。

有什么方法可以等待它登录然后路由器将我推到仪表板。

我对此很陌生,任何帮助将不胜感激。

//routes 

export const routes = [
  {
    path: "/adduser",
    component: AddUser,
    meta: {
      requiresAuth: true
    }
  },
  {
    name: "details",
    path: "/details/:id",
    component: User,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: "/register",
    component: Register,
    meta: {
      requiresGuest: true
    }
  },
  {
    path: "/login",
    component: Login,
    meta: {
      requiresGuest: true
    }
  },
  {
    path: "/dashboard",
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: "/",
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    name: "editUser",
    path: "edituser/:id",
    component: EditUser,
    meta: {
      requiresAuth: true
    }
  }
];

//the login function 

 emailLogin(email, password) {
      firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then(this.$router.push("/dashboard"))
        .then(() => {
          this.$store.dispatch("auth/login");
        });
    }

//the router guard

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!firebase.auth().currentUser) {
      next({
        path: "/login",
        query: {
          redirect: to.fullPath
        }
      });
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.requiresGuest)) {
    if (firebase.auth().currentUser) {
      next({
        path: "/"
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

标签: javascriptfirebasevue.jsvue-router

解决方案


then(this.$router.push("/dashboard"))push 内部给出了一个应该返回给箭头函数的承诺。

所以新的登录功能将是:

emailLogin(email, password) {
      firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then(() => {
          this.$router.push("/dashboard");
        })
        .then(() => {
          this.$store.dispatch("auth/login");
        });
    }

推荐阅读