Vue.js 无法更改方法内的数据值

ala*_*nko 3 firebase vue.js

任何人都可以帮助我为什么我无法在方法中更改数据值?

    <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>
Run Code Online (Sandbox Code Playgroud)

“console.log”正在工作,我可以从 Firestore 获取值,但是为什么“name”的值没有改变?

Jac*_*Goh 5

this将不再引用 Vue 实例function(){},因为这种函数声明绑定了它自己的this.

所以你可以保存this到另一个变量 1st 中,并在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
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用箭头函数,如()=>{}. 箭头函数不绑定自己的this. 但在某些浏览器中尚不支持