【问题标题】:how to solve error "this is undefine" in vue 3如何解决 vue 3 中的错误“这是未定义的”
【发布时间】:2018-09-28 09:47:26
【问题描述】:

我已经创建了一个像下面这样的 vue 组件:

<template>
    <div class="login">
        <h3>Sign in</h3>
        <input type="text" placeholder="Email" v-model="email"/><br>
        <input type="password" placeholder="Password" v-model="password"/><br>
        <button v-on:click="login()">Login</button>
    </div>
</template>

<script>
    import firebase from 'firebase'

    export default {
        name: "Login",
        data: function () {
            return {
                email: '',
                password: ''
            }
        },
        methods: {
            login: function () {
                firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(function (user) {
                    this.$router.replace('home')
                })
            }
        }
    }
</script>

在我输入用户名和密码并单击登录、firebase 身份验证成功和控制台显示错误这是未定义之前,仍然可以。 我该如何解决这个错误?我无法使用路由器。

【问题讨论】:

  • 尝试在then回调中使用箭头函数或在函数外部存储对this的引用。

标签: javascript vue-component vue-router


【解决方案1】:

尝试使用箭头函数:

firebase.auth().signInWithEmailAndPassword(this.email, this.password).then((user) => {
    this.$router.replace('home')
})

【讨论】:

    【解决方案2】:
    login: function () {
       let vm=this
       firebase.auth().signInWithEmailAndPassword(this.email,  this.password).then(function (user) {
                        vm.$router.replace('home')
                    })
                }
    

    【讨论】:

      【解决方案3】:

      带有then 的回调函数没有可用的login 函数的上下文。如果您能够使用 ES6,请改用箭头函数:

       login: function () {
                  firebase.auth().signInWithEmailAndPassword(this.email, this.password).then((user) => {
                      this.$router.replace('home')
                  })
              }
      

      但是,如果你因为某种原因不能使用 ES6,尝试存储一个对 this 的引用并在函数中使用它:

       login: function () {
                 var self = this;
                  firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(function (user) {
                      self.$router.replace('home')
                  })
              }
      

      【讨论】:

        【解决方案4】:

        使用箭头函数或 bind() 方法 示例:

        foo().then(() => {
             // access this
        })
        // or
        foo().then(function() {
             // access this
        }.bind(this))
        

        【讨论】:

          猜你喜欢
          • 2020-12-11
          • 2021-10-18
          • 2021-03-28
          • 2021-11-04
          • 1970-01-01
          • 1970-01-01
          • 2018-10-14
          • 1970-01-01
          • 2021-06-01
          相关资源
          最近更新 更多