Vue路由器推送未定义

时间:2020-04-09 17:12:49

标签: javascript firebase vue.js vuex quasar

我使用Quasar框架设计UI。当我使用函数注销并使用vue-router推送到另一条路由时,出现以下错误:

TypeError: Cannot read property 'push' of undefined

我使用vuex操作方法注销并替换:

export const handleAuthStateChanged = ({ commit }, payload) => {
  firebaseAuth.onAuthStateChanged(function(user) {
    if (user) {
      // user is logged in
      let userId = firebaseAuth.currentUser.uid;
      firebaseDB.ref("users/" + userId).once("value", function(snapshot) {
        let userDetails = snapshot.val();
        commit("USER_DETAILS", {
          name: userDetails.name,
          email: userDetails.email,
          online: userDetails.online,
          type: userDetails.type,
          userId: userId
        });
      });
      this.$router.push('');
    } else {
      // user is logged out
      commit("USER_DETAILS", {});
      this.$router.replace('chat');
    }
  });
};

我该如何解决?

3 个答案:

答案 0 :(得分:1)

任何新函数都将定义自己的this值。在回调this中,不再指向原始Vue实例“ this”。

尝试更改:

firebaseAuth.onAuthStateChanged(function(user) { ...

到箭头功能:

firebaseAuth.onAuthStateChanged((user) => { ...

this将正确引用定义了$router的原始Vue实例。

答案 1 :(得分:1)

有两个问题:

  • @MisterCurtis的答案已经涵盖了this上下文问题

    普通函数具有自己的this上下文,而es6箭头函数继承了它。一些reading

  • this.$router仅在this是组件实例时才有意义。 Vue将router插入其实例原型。但是这段代码是Vuex动作,而不是实例方法。

要在外部模块(例如Vuex)或任何其他模块中使用vue-router,可以将其导入:

import router from '@/router'

然后使用

router.push

代替this.$router.push

一种替代方法是在登录组件中管理身份验证结果,并在其中使用this.$router

答案 2 :(得分:0)

谢谢大家尝试解决我的问题。我在不使用vuex动作中使用箭头功能的情况下修复了它。

export const handleAuthStateChanged = function ({ commit }, payload) {
...