必须两次单击登录按钮;使用vue-router和Firebase身份验证

时间:2020-07-12 14:22:20

标签: javascript firebase vue.js vue-router

我已经设置了路由器防护,因此当我登录而不是将路由器第二次推入仪表板时,它需要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();
  }
});

1 个答案:

答案 0 :(得分:1)

then(this.$router.push("/dashboard"))内,推入给出了应许,应将其返回给箭头函数。

因此新的登录功能将是:

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