4

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

    <head>
    <script src="https://unpkg.com/[email protected]/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?

2
  • 2
    syntax error in name = "". It should be name:"" Commented Mar 30, 2018 at 9:23
  • @JacobGoh I am sorry that I made the mistake in this post, the real code is name: "", not name = "" Commented Mar 30, 2018 at 9:28

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.