简体   繁体   English

VueJS + Firebase数据推送

[英]vuejs + firebase data push

Component code: 组件代码:

  let booksRef = db.ref().child('books')
  export default {
    name: 'google-map',
    firebase: function () {
      return {
        books: booksRef
      }
    },
    data: function () {
      return {
        markerCoordinates: [],
        markers: []
      }
    },
    created: function () {
      booksRef.on('value', snap => {
        snap.forEach(childSnap => {
          var childVal = childSnap.val();
           this.markerCoordinates = childVal.position;
        });
      });

    },
    mounted: function () {
      const element = document.getElementById(this.mapName)
      const mapCentre = this.markerCoordinates[0]
      const options = {
        center: new google.maps.LatLng(mapCentre.latitude, mapCentre.longitude)
      }
      this.map = new google.maps.Map(element, options);
      this.markerCoordinates.forEach((coord) => {
        const position = new google.maps.LatLng(coord.latitude, coord.longitude);
        const marker = new google.maps.Marker({
          position,
          map: this.map
        });
        this.markers.push(marker)
      });
    }
  };

error capture : 错误捕获:

I want to expose markers stored in firebase Why does not the markerCoordinates contain data? 我要公开存储在Firebase中的标记,为什么markerCoordinates不包含数据?

The problem is that you establish a connection to listen on values for your collection, and at the moment you try to access the this.markerCoordinates it is empty (so this error is because the lifecycle and asynchronous handling). 问题在于您建立了一个连接以侦听您的集合的值,并且此刻您尝试访问this.markerCoordinates为空(因此,此错误是由于生命周期和异步处理)。 There are some solutions here: 这里有一些解决方案:

  1. Move your Firebase listener ( created hook) to the on mounted hook and then call the code you have in the mounted lifecycle hook (you can create a separate method for this and call it once this.markerCoordinates is not empty) 将Firebase侦听器(已created钩子)移动到已mounted钩子上,然后调用已mounted生命周期钩子中的代码(您可以为此创建单独的方法,并在this.markerCoordinates不为空时调用它)
  2. I see you are using Vuefire bindings, you should stick to how the structure is suggested there 我看到您正在使用Vuefire绑定,您应该坚持那里的结构建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM