Answer a question

Can anyone help me why I cannot be able to change the data value within a method?

    <head>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
    </head>
    <body>
    <script>
    var app = new Vue({
      data() {
        return {
          name: ""
        }
      },
    methods: {
      firebase: function() {
        var docRef = db.doc("test/testdoc");
        docRef.get().then(function(doc) {
          this.name = doc.data().name;    //this one not working
          console.log(doc.data().name);   //just to test wether I can get data from Firestore
        })
      }
    })
    </script>
    </body>

"console.log" is working and I can get the value from Firestore, but why the value of "name" doesn't change?

Answers

this will not be referring to the Vue instance anymore in function(){}, because this kind of function declaration bind its own this.

So you can save this into another variable 1st, and use it in function(){}.

methods: {
  firebase: function() {
    var docRef = db.doc("test/testdoc");
    var _this = this; // save it in a variable for usage inside function
    docRef.get().then(function(doc) {
        _this.name = doc.data().name;    //this one not working
      console.log(doc.data().name);   //just to test wether I can get data from Firestore
    })
  }
}

Alternatively, you could use arrow function like ()=>{}. Arrow function doesn't bind its own this. But it's not supported in some browsers yet.

Logo

前往低代码交流专区

更多推荐