【问题标题】:Vue.js cannot change data value within a methodVue.js 无法在方法中更改数据值
【发布时间】:2018-09-09 08:03:41
【问题描述】:

谁能帮助我为什么我不能在方法中更改数据值?

    <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”正在运行,我可以从 Firestore 获取值,但为什么“name”的值没有改变?

【问题讨论】:

  • name = "" 中的语法错误。应该是name:""
  • @JacobGoh 很抱歉我在这个帖子里弄错了,真正的代码是 name:"",而不是 name = ""

标签: firebase vue.js


【解决方案1】:

this 将不再引用function(){} 中的 Vue 实例,因为这种函数声明绑定了它自己的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
    })
  }
}

或者,您可以使用 ()=&gt;{} 之类的箭头函数。箭头函数不绑定自己的this。但它是not supported in some browsers

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 2019-10-03
    • 2020-10-23
    • 2017-06-13
    • 2020-10-30
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多