繁体   English   中英

如何解决vue 3中的错误“ this is undefined”

[英]how to solve error “this is undefine” in vue 3

我已经创建了一个像下面这样的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身份验证成功”和“控制台显示错误”(这是未定义的),它仍然可以。 我该如何解决这个错误? 我不能使用路由器。

尝试使用箭头功能:

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

与回调函数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')
            })
        }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM