簡體   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