[英]how to solve error “this is undefine” in vue 3
I have create a vue component like bellow: 我已经创建了一个像下面这样的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>
It's still ok until I enter username and password and click Login, firebase auth success and console show error this is undefined. 直到我输入用户名和密码并单击“登录”,“ firebase身份验证成功”和“控制台显示错误”(这是未定义的),它仍然可以。 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. 与回调函数
then
没有的情况下login
的功能提供给它。 If you're able to use ES6, use an arrow function instead : 如果您可以使用ES6,请改用箭头功能:
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 : 但是,如果由于某种原因您无法使用ES6,请尝试存储
this
的引用并在函数中使用它:
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: 使用箭头函数或bind()方法示例:
foo().then(() => {
// access this
})
// or
foo().then(function() {
// access this
}.bind(this))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.