【问题标题】:Cannot read property '$router' of undefined?无法读取未定义的属性“$router”?
【发布时间】:2019-03-22 22:10:20
【问题描述】:

我正在尝试让用户可以登录页面,但向我显示此消息“无法读取未定义的属性 '$router'”

我在 Vue 中的登录代码,在 Export default 里面

import {fb} from "../firebase";
import router from '../router';

export default {
 name: "NavBar",
 components: {...},
 data() {
   return {
    login: false,
    register: false,
    name: null,
    email: null,
    pwd: null,
  };
 },
methods: {
logInner(){
      fb.auth().signInWithEmailAndPassword(this.email, this.pwd)
          .then(function(){
          this.$router.replace('users');
          })
          .catch(function(error) {`enter code here`
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;
              if (errorCode === 'auth/wrong-password') {
                  alert('Wrong password.');
              } else {
                  alert(errorMessage);
              }
              console.log(error);
      });

  },
registering() {
  fb.auth().createUserWithEmailAndPassword(this.email, this.pwd)
    .then((user) =>{
      this.$router.replace('users');
    })
    .catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      if (errorCode == "auth/weak-password") {
        alert("The password is too weak.");
      } else {
        alert(errorMessage);
      }
      console.log(error);
     });
   }
 }
 };

我试过 router.push 甚至 router.go 都没有帮助。 有人可以帮帮我吗?

【问题讨论】:

  • 不应该是router 而不是this.$router ?

标签: javascript vue.js


【解决方案1】:

this 在 fb.auth() 函数中不可用,因此请尝试以下操作。有关详细说明,请查看此答案:https://stackoverflow.com/a/47148828/9489397

logInner(){
let self = this
      fb.auth().signInWithEmailAndPassword(this.email, this.pwd)
          .then(function(){
          self.$router.replace('users');
          })

registering() {
let self = this
  fb.auth().createUserWithEmailAndPassword(this.email, this.pwd)
    .then((user) =>{
      self.$router.replace('users');
    })

【讨论】:

  • 您也可以在回调中使用箭头函数,以避免必须声明“self”变量
猜你喜欢
  • 2019-11-22
  • 2021-12-08
  • 2016-01-31
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多