【问题标题】:am trying to redirect the user but the this.$router.push('/') is giving me undefined我试图重定向用户,但 this.$router.push('/') 给了我 undefined
【发布时间】:2020-09-01 03:20:19
【问题描述】:

我试图在用户注销时将用户重定向到欢迎页面,并在用户重新登录时将用户重定向到主页。但是 this.$router.push('/') 给了我未定义的信息。

这里是代码

handleAuthStateChanged: ({ commit }) => {
    auth.onAuthStateChanged(user => {
      if (user) {
        commit("setLogin", true);
        console.log("login");
        //get current user details
        let userId = auth.currentUser.uid;
        db.collection("users")
          .doc(userId)
          .get()
          .then(snapshot => {
            if (snapshot.exists) {
              let currentUser = snapshot.data();
              commit("setUser", currentUser);
              console.log(currentUser);
            } else {
              // snapshot.data() will be undefined in this case
              console.log("No such document!");
            }
          });
        this.$router.push("/");
      } else {
        console.log("logout");
        commit("setLogin", false);
        commit("setUser", null);

        this.$router.replace("/welcome");
      }
    });
  }

enter image description here

【问题讨论】:

    标签: firebase vue.js vuex vue-router


    【解决方案1】:

    您正在onAuthStateChanged 函数范围内访问this,这意味着该范围内的this 将引用自己的函数(因为您使用的是箭头函数),而不是Vue 实例。

    这行不通:

    handleAuthStateChanged: ({ commit }) => {
        auth.onAuthStateChanged(user => {
            ...
            // `this` is not a Vue instance
            this.$router.push("/");
        })
    }
    

    你需要先在作用域外创建一个引用 Vue 实例的变量,这样你就可以在函数作用域内调用它,例如:

    handleAuthStateChanged: ({ commit }) => {
        const self = this;
        auth.onAuthStateChanged(user => {
            ...
            // `this` is not a Vue instance, but `self` is
            self.$router.push("/");
        })
    }
    

    或者不要使用箭头函数,因为箭头函数内部的this指的是它自己的函数,例如:

    handleAuthStateChanged: ({ commit }) => {
        auth.onAuthStateChanged(function(user) {
            ...
            // `this` is a Vue instance 
            this.$router.push("/");
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2021-02-10
      • 2020-07-01
      • 1970-01-01
      • 2022-01-21
      • 2021-01-08
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多