#firebase #vue.js
#firebase #vue.js
Вопрос:
Я пытаюсь получить доступ к, data variable
вызываемой localUser
из функции внутри функции метода. Но, насколько я могу судить из сообщения об ошибке, я думаю, что он просто не может получить доступ localUser
из data
.
Это сообщение об ошибке, которое я получаю:
Не перехвачено (в обещании) Ошибка типа: не удается установить для свойства ‘LocalUser’ значение undefined при оценке (Form.vue?c13f:100) в auth.js:1361
Я отметил, где проблема в коде с комментарием:
// ОШИБКА — не удается получить доступ к этому.LocalUser
Что я пробовал:
- Используя
this.$data.localUser
-
Помещаем ее в
.then
функцию послеfirebase.auth().onAuthStateChanged( (user) => {}
функции, как в приведенном ниже коде, который действительно работал, но я не могу этого сделать с.then
, я должен сделать это внутри:firebase.auth().onAuthStateChanged((пользователь) => {}
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
}).then(() => {
firebase.auth().onAuthStateChanged( (user) => {
if (user) {
// If already signed in
const db = firebase.firestore();
this.localUser = user;
console.log(this.localUser);
db.collection("users").doc(this.localUser.uid).set({
firstName: this.firstName,
lastName: this.lastName,
student: this.student,
teacher: this.teacher,
email: this.email,
password: this.password
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
})
})
Код, который я использую и в котором проблема заключается в строке 96:
<template>
<div id="signup-form-con" v-if="!connected">
<form id="signup-form" @submit.prevent>
<input v-model='firstName' type="text" id="signup-name" placeholder='First name'><br />
<input v-model='lastName' type="text" id="signup-surname" placeholder='Last name'><br />
<input v-model='student' type="checkbox"><span class='checkbox-label'>Student</span>
<input v-model='teacher' type="checkbox"><span class='checkbox-label'>Teacher</span><br />
<input v-model='email' type="email" id="signup-email"><br />
<input v-model='password' type="password" placeholder='Password'>
<input v-model='confirmed' type="password" placeholder='Confirm'><br />
<span>Sign in instead</span>
<button @click='EmailSignIn'>Next</button>
</form>
<div class="auto-signup">
<span id="or-use">Or use</span>
<div class="buttons">
<button id="google-signup" @click='GoogleSignIn'>
<img src="" alt="" id="google-img-signup">
</button>
<button id="facebook-signup" @click='FacebookSignIn'>
<img src="" alt="" id="fb-img-signup">
</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Form",
props: {
connected: false
},
data: function() {
return {
localUser: null,
firstName: null,
lastName: null,
student: false,
teacher: false,
email: null,
password: null,
confirmed: null
}
},
methods: {
EmailSignIn: function() {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
firebase.auth().onAuthStateChanged( (user) => {
if (user) {
// If already signed in
const db = firebase.firestore();
// THE BUG - cannot access this.localUser
this.localUser = user;
console.log(this.localUser);
db.collection("users").doc(this.localUser.uid).set({
firstName: this.firstName,
lastName: this.lastName,
student: this.student,
teacher: this.teacher,
email: this.email,
password: this.password
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
})
}).then(() => {
})
}
</script>
<style scoped lang="sass"></style>
Ответ №1:
Я не понимаю, почему вы выполняете весь код (по крайней мере, все, что вы показываете) в обработчике ошибок, но причина, по которой вы не можете получить доступ к контексту Vue, заключается в обработчике ошибок [переформатирован для ясности]:
firebase.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.catch(function(error) {
// all your code is here
})
Вы можете привести контекст в соответствие, изменив его на функцию со стрелкой:
firebase.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.catch((error) => {
// all your code is here
})