组件代码:
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不包含数据?
答案 0 :(得分:0)
问题是您建立了一个连接以侦听您的集合的值,并且在您尝试访问this.markerCoordinates
的那一刻它是空的(所以此错误是因为生命周期和异步处理)。这里有一些解决方案:
created
钩)移到mounted
钩上,然后调用mounted
生命周期钩中的代码(您可以为此创建一个单独的方法, this.markerCoordinates
不为空时调用它)