将用户数据从firebase auth分配到我的本地变量时遇到问题。在Vue实例中,创建了生命周期挂钩,我为身份验证状态调用firebase auth函数,在该函数调用中,我想将用户数据分配给fireUser变量。我将console.log放在它后面,并且打印正确,但是如果我想在页面上显示它为空白(空)。我认为这与promise有关,但不能放在一起。谢谢,提前寻求帮助。



  let storage = firebase.initializeApp(config);
  let db = storage.database();
  let usersRef = db.ref('users');








//Vue instance

var app = new Vue({
  el: '#app',
  firebase:{
      userDb:usersRef
  },
  data: {
    person:{
      email:'',
      password:''
    },
    user:{
      name:'',
      description:'',
      photourl:'',
      learningjournal:''
    },
    users:[],
    fireUser:''


  },
  methods:{
    //Posting data to Firebase
    submit(){
      usersRef.push(this.user);
      this.user = '';
    },
    register(){
      firebase.auth().createUserWithEmailAndPassword(this.person.email, this.person.password).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
      });

      this.person= '';
    },
    login(){
      firebase.auth().signInWithEmailAndPassword(this.person.email, this.person.password).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
      });


    },
    logOut(){
      firebase.auth().signOut().then(function() {
          // Sign-out successful.
          console.log('logout');
        }).catch(function(error) {
          // An error happened.
        });
    }
  },
  created(){
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        this.fireUser = user;
        console.log(user);
        console.log('user',this.fireUser);

      } else {
        // No user is signed in.
      }
    });
  }


});

<html>
  <head>
    <title>SEPCO: Elium September Cohort Page</title>
    <link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet">
  </head>
  <body>
    <div class="pimg">
      <div class="ui two column centered grid">
        <h1 class="ui column inverted black center aligned header"><i class="fa fa-graduation-cap" aria-hidden="true"></i>SEPCO <br> <hr> <em>Elium September Cohort Page</em></h1>
      </div>
    </div>
    <div class='ui container'>
      <br>
    <br> <br>

    <h2 class="ui olive inverted segment center aligned header">Welcome</h2>
    <p id='introduction'>This is the collaborative page of the Elium September cohort. This is the beginning of a collaborative document and it <b>urgently needs your input!</b> So please go into the code, and make this page prettier, smarter, more content rich and of course more JavaScript-enriched.</p>
    <i>Our clan name on codewars.com: SEPCO</i>
   <div id='countdown'>
 <!-- who wants to code up a count-down to the startdate of the bootcamp?? -->
    </div>
    <div class="ui grid">
      <div class="sixteen wide tablet eight wide computer column">
        <h2 class="ui olive inverted segment center aligned header"> Basics of how we want to prepare together.</h2>
        <ol class="ui list">
          <li> Meet, decide on milestones togehter, then share how far you got e.g. using polls in Slack (for example "Did everyone finish watchandcode.com course?")</li>
          <li> Scheduled hangout time for 2 hours everyday where people will be online working/studying which is non-mandatory. (doodle invite #1)
            <ol>
              <li><a href="https://doodle.com/poll/cz8igzmkew2vabfh" target="_blank">Click here to post availability to hangout</a></li>
            </ol>
          </li>
          <li>
             A Code Wars problem once a week every Friday starting Sept 28th. (doodle invite #2) answer will be on plunkr
            <ol>
              <li><a href="https://doodle.com/poll/k6kg6tk7ce4ipmnq" target="_blank">Click here to post time availability for Code Wars problem</a></li>
            </ol>
          </li>
          <li> Share your plunker/codepen/glitch sites! There's two ways how we recommend doing this:
            <ol>
              <li> We will use  these codesharing-site accounts to share to the group what we have learned ( Share fun projects! And Code wars problems after completion)</li>
              <li> Make a learning journal where you write down what you learned and what your personal goals are, this is also the ideal place to link to any other plunker/codepen/glitch creation you've made. The URL to this learning journal should be put into your object (see Part 3. below)</li>
            </ol>
          </li>
          <li> HTML and CSS discussed more in 2 weeks (because this can be learned towards the end)</li>
        </ol>
      </div>
      <div class="sixteen wide tablet eight wide computer column">
        <h2 class="ui olive inverted segment  center aligned header">Shared Milestones</h2>
        <p class="ui center aligned header">We want to get the following done by September 10th.</p>
          <ul id="meetingPoints">
            <li class="ui padded segment"> <strong>DECIDED:</strong>  Complete practical javascript ("PJS") on watchandcode</li>
            <li class="ui padded segment"> <strong>PROPOSED:</strong> Additional JavaScript (define list of skills/concepts)</li>
            <li class="ui padded segment"> <strong>REVISIT:</strong> first week of August: Basic HTML</li>
            <li class="ui padded segment"> <strong>REVISIT:</strong> first week of August: Basic CSS</li>
            <li class="ui padded segment"> <strong>REVISIT:</strong> first week of August: GIT</li>
        </ul>
      </div>
    </div>






 <br>
      <h2 class="ui olive inverted segment center aligned header"> Info on the cohort members & links to their learning journals on plunker </h2>
      <p>The cohort is an array and every member is an object. Dive into the sourcecode and add an object with your details. And then we asap need someone who makes this section better/prettier (see sourcecode)</p>
     <br> <br>

    <!-- loop and create Info card Using Vue.js -->
     <div id="app"> <!--Starting vue instance here-->
       <div class="ui form">
         <div class="fields">
           <div class="field">
             <label>Email</label>
             <input type="text" placeholder="Email" v-model='person.email'>
           </div>
           <div class="field">
             <label>Password</label>
             <input type="password" v-model='person.password'>
           </div>
         </div>
         <button class="ui blue button" @click.prevent="register">Submit</button>
         <br>
         <div class="ui form">
           <div class="fields">
             <div class="field">
               <label>Email</label>
               <input type="text" placeholder="Email" v-model='person.email'>
             </div>
             <div class="field">
               <label>Password</label>
               <input type="password" v-model='person.password'>
             </div>
           </div>
           <button class="ui blue button" @click.prevent="login">Submit</button>
           <br>
           <hr>
           <!-- I want to print User loged in result here -->
           <p>{{fireUser}}</p>
           <hr>
           <br>

       </div>
       <br>
       <div class="ui grid">
         <div class="ui four wide column" v-for="people in userDb">
          <div class="ui card">
            <div class="image">
              <img :src="people.photourl">
            </div>
            <div class="content">
              <div class="header">{{people.name}}</div>
              <div class="description">
                <p>{{people.description}}</p>
              </div>
              <br>
              <div class="extra content">
                <span class="left floated">
                  <i class="arrow down icon"></i>
                  <a :href="people.learningjournal">Plunker</a>
                </span>
              </div>
            </div>
          </div>
        </div>
       </div>

     <br><br><br>
     <!-- Form for making users cards -->

     <form class="ui form">
       <div class="field">
         <label>First/Last-Name:</label>
         <input type="text" v-model="user.name"  placeholder="First/Last Name">
       </div>
       <div class="field">
          <label>Description of You:</label>
          <textarea v-model="user.description"></textarea>
       </div>
       <div class="field">
         <label>Picture Url:</label>
         <input type="text" v-model="user.photourl"  placeholder="Picture Url">
       </div>
       <div class="field">
         <label>Plunker Url:</label>
         <input type="text" v-model="user.learningjournal" placeholder="Plunker Url">
       </div>
       <button class="ui olive  button" @click.prevent="submit">Submit</button>
     </form
     <br>
    <button class="ui button" @click.prevent='logOut'>click me</button>

     <br>
  </div> <!--end of vue instance-->
<div id="footer"><hr></div>

    <!-- Your web-app is https, so your scripts need to be too -->
    <script src="https://code.jquery.com/jquery-2.2.1.min.js"
            integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00="
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
    <script src="https://unpkg.com/vuefire/dist/vuefire.js"></script>
    <script src="client.js"></script>
  </div>

  </body>
</html>

最佳答案

回调中的this变量未引用Vue实例。

您需要在回调之外设置对Vue实例的引用,然后在设置响应中的数据时使用该引用:

created(){
  let self = this;
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      self.fireUser = user;
...

09-25 16:45
查看更多