【问题标题】:Calling 'this' inside of firebase once function在 firebase 一次函数中调用“this”
【发布时间】:2017-12-26 17:01:40
【问题描述】:

所以我正在创建一个 Vuejs 应用程序,并尝试在组件挂载时获取 firebase 数据。这是可行的,但我尝试将值写入 vuejs 数据属性。为此,我只会在 firebase 函数中调用 this.property = snapshot.val();(参见下面的代码),但这不起作用:this is undefined

所以我的代码就是:

export default {
  data() {
    return {
      imageList: "No images!"
    }
  },
  mounted() {
    if (!firebase.apps.length) {
      // Initialize Firebase
      var config = {
        ...
      };

      firebase.initializeApp(config);

      var database = firebase.database();
      var ref = database.ref("images").orderByChild("date");


    firebase.database().ref("images/").once('value').then(function(snapshot) {
        this.imageList= snapshot.val();
      });
    }
  }
}

我尝试在函数外部调用 this.imageList= snapshot.val(); 并使用一个变量来存储值,“this”不再未定义,但由于请求尚未完成,因此数据不存在。

所以基本上我想得到 snapshot.val();进入 this.imageList!

提前致谢。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database vue.js vue-component


    【解决方案1】:

    你可以使用 es6 箭头函数语法来解决这个问题。

    firebase.database().ref("images/").once('value').then((snapshot) => {
        this.imageList= snapshot.val();
    });
    

    或将 this 绑定到函数的上下文。

    var that = this;
    

    【讨论】:

    • 我试试看!谢谢!
    【解决方案2】:

    使用箭头函数、闭包或bind

    firebase.database().ref("images/").once('value').then(snapshot => {
      this.imageList= snapshot.val();
    });
    

    How to access the correct this inside a callback

    【讨论】:

      【解决方案3】:

      您也可以使用bind

      firebase.database().ref('images/').once('value').then(function(snapshot) {
        this.imageList = snapshot.val()
      }.bind(this))
      

      【讨论】:

      • 我尝试过这种方式绑定,但没有成功,但也许我遗漏了什么,谢谢!
      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2018-10-02
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多