I have create a vue component like bellow:
<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>
It's still ok until I enter username and password and click Login, firebase auth success and console show error this is undefined. How can I solve this error? I cannot use router.
Try with an arrow function instead:
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')
})
}
The callback function with the then
does not have the context of login
function available to it. If you're able to use ES6, use an arrow function instead :
login: function () {
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then((user) => {
this.$router.replace('home')
})
}
However, if you for some reason are not able to use ES6, try storing a reference to this
and use it inside the function :
login: function () {
var self = this;
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(function (user) {
self.$router.replace('home')
})
}
Using arrow function or bind() method Example:
foo().then(() => {
// access this
})
// or
foo().then(function() {
// access this
}.bind(this))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.