【问题标题】:vuejs + firebase data pushvuejs + firebase 数据推送
【发布时间】:2018-11-01 05:30:59
【问题描述】:

组件代码:

  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)
      });
    }
  };

错误捕获:

我想公开存储在 firebase 中的标记 为什么 markerCoordinates 不包含数据?

【问题讨论】:

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


    【解决方案1】:

    问题是你建立了一个连接来监听你的集合的值,而在你尝试访问this.markerCoordinates的那一刻它是空的(所以这个错误是因为生命周期和异步处理)。这里有一些解决方案:

    1. 将您的 Firebase 侦听器(created 钩子)移动到 on mounted 钩子,然后调用您在 mounted 生命周期钩子中的代码(您可以为此创建一个单独的方法并调用它一次 this.markerCoordinates不为空)
    2. 我看到你正在使用Vuefire 绑定,你应该坚持那里建议的结构

    【讨论】:

    • 无法理解我需要一个粗略的来源
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多