VUE - FIREBASE | Как получить профиль пользователя из базы данных в реальном времени - PullRequest
0 голосов
/ 01 апреля 2020

Я получил профиль пользователя из базы данных Realtime, но когда у меня более 1 учетной записи, я также получаю второй профиль пользователя.

Здесь ниже вы видите данные от 2 пользователей. Но я хочу, чтобы пользователь входил в систему под именем currentUser

. Идентификатор: currentUser

enter image description here

Это база данных в реальном времени:

enter image description here

Это мой профиль. vue страница :

          <div class="container" v-for="profileData of profile" :key="profileData['.key']">
            <div v-if="seen" class="row">
              <div class="col">
                <div class="card card-border" style="width: 30rem;">
                  <div class="card-body">
                    <h4 class="card-title text-center mb-4">Personal information</h4>
                      <p class="card-text">ID: {{profileData.CurrentUser}}</p>
                      <p class="card-text">First name: {{profileData.firstName}}</p>
                      <p class="card-text">Last name: {{profileData.lastName}}</p>
                      <p class="card-text">Phone number: {{profileData.phoneNumber}}</p>
                      <p class="card-text">Adress: {{profileData.adress}}</p>
                      <p class="card-text">Citizenship: {{profileData.citizenship}}</p>
                      <p class="card-text">Personal email: {{profileData.personalEmail}}</p>
                  </div>
                </div>
              </div>
              <div class="col"></div>
              <div class="col">
                <div class="card card-border" style="width: 30rem;">
                  <div class="card-body">
                    <h4 class="card-title text-center mb-3">Business information</h4>
                      <p>Company name: {{profileData.companyName}}</p>
                      <p>Chamber Of Commerce Number: {{profileData.chamberOfCommerceNumber}}</p>
                      <p>Street: {{profileData.street}}</p>
                      <p>House number: {{profileData.houseNumber}}</p>
                      <p>ZIP code: {{profileData.zipCode}}</p>
                      <p>Location: {{profileData.location}}</p>
                      <p>Company email: {{profileData.companyEmail}}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

Я добавил if / else в раздел create () ниже.

И это скрипт:

<script>
import firebase from "firebase";
import { db } from '../../config/db';

export default {
  data() {
    return {
      email: "",
      password: "",
      profileData: [],
      isHidden: true,
      seen: true,
      isLoggedIn: false
    }
  },
  firebase: {
    profile: db.ref('profile')
  },
  methods: {
    resetPassword() {
      const auth = firebase.auth();
      auth.sendPasswordResetEmail(auth.currentUser.email).then(() => {
        console.log('Email send');
        // Email sent.
      }).catch((error) => {
        // An error happened.
        console.log(error);
      });
    }
  },
  created() {
    if(firebase.auth().currentUser) {
      this.isLoggedIn = true;
      this.currentUser = firebase.auth().currentUser.email;
    }
    var user = firebase.auth().currentUser;
    if (this.user == this.profileData.CurrentUser) {
      this.seen = true;
    } else {
      this.seen = false;
    }
  }
};
</script>

В этом профиле. vue страница У меня есть функция добавления :

AddProfile() {
            console.log(JSON.stringify(this.profileData) + this.currentUser)
            this.$firebaseRefs.profile.push({
                firstName: this.profileData.firstName,
                lastName: this.profileData.lastName,
                phoneNumber: this.profileData.phoneNumber,
                adress: this.profileData.adress,
                citizenship: this.profileData.citizenship,
                personalEmail: this.profileData.personalEmail,
                companyName: this.profileData.companyName,
                chamberOfCommerceNumber: this.profileData.chamberOfCommerceNumber,
                street: this.profileData.street,
                houseNumber: this.profileData.houseNumber,
                zipCode: this.profileData.zipCode,
                location: this.profileData.location,
                companyEmail: this.profileData.companyEmail,
                CurrentUser: this.currentUser
            })
            this.profileData.firstName = '';
            this.profileData.lastName = '';
            this.profileData.phoneNumber = '';
            this.profileData.adress = '';
            this.profileData.personalEmail = '';
            this.profileData.companyName = '';
            this.profileData.chamberOfCommerceNumber = '';
            this.profileData.street = '';
            this.profileData.houseNumber = '';
            this.profileData.zipCode = '';
            this.profileData.location = '';
            this.profileData.companyEmail = '';
            this.CurrentUser = '';
            window.scrollTo(0,0, 0,0);
            console.log('Added to database');
            /* Waiting for 2 seconds here */
            this.$router.push('/internship')
        },

1 Ответ

0 голосов
/ 01 апреля 2020

По-видимому, вы используете Vuefire .

Как вы увидите в документации Vuefire, делая

firebase: {
  profile: db.ref('profile')
},

, вы используете декларативные ставки на узле profile Realtime Database и, следовательно, , это нормально, что вы получаете все дочерние элементы этого узла .


Если вы просто хотите отобразить соответствующий узел текущему пользователю можно использовать привязку programmati c в следующих строках:

<template>
  <div class="home">
    {{user}}
    <ol></ol>
  </div>
</template>

<script>
import { db } from "../firebase";
const profile = db.ref("profile");
export default {
  name: "demo",
  data() {
    return {
      user: null,
      id: null
    };
  },
  watch: {
    id: {
      immediate: true,
      handler(id) {
        this.$rtdbBind("user", profile.child(id));
      }
    }
  },
  created() {

    if (firebase.auth().currentUser) {
      this.id = currentUser.uid;
    }
  }
};
</script>
...