繁体   English   中英

无法将 Firebase 实时数据库中的数据保存到 Vue.js 中的数组,并将其用于在 Vue2-google-maps 上显示标记

[英]Cannot save data from Firebase realtime database to array in Vue.js, and use it for displaying markers on Vue2-google-maps

我在将数据从 Firebase 实时数据库保存到 Vue 组件内的数组时遇到问题。

我得到的主要错误是:“无法读取 null 的属性 'savedLocations' ”。

该数组应该包含有关帖子的信息; 包括标题、描述、图像和用户的位置。 每个位置都作为原始地址和地理位置(lat,lng)保存到数据库中,目标是在 vue2-google-maps map 上显示标记。

包含有关帖子的所有信息的表单数据正在另一个视图中提交,所以我的主要问题是从 firebase 检索数据并在 map 上显示标记。

我收到错误的当前代码是:

export default {

data() {
    return {
        // check for sign in:
        signedIn: false,

        // map information
        map: null,
        myCoordinates: {
            lat: 0,
            lng: 0
        },
        zoom: 12,

        // locations:
        savedLocations: []
    }
},
async beforeMount() {

    // reference to list of posts
    var ref = db.ref("PhotoGallery");

    ref.on("value", function(snapshot) {
        snapshot.forEach((childSnapshot) => {
            this.savedLocations.push(childSnapshot.val());
        })
    }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    });
}

如果我 console.log 所有 childSnapshots,我确实从数据库 output 中获取所有项目作为控制台中的对象,每个单独的,但我不知道如何将它们 append 到一个数组,所以我可以遍历它们并基于标记关于他们的地理位置。

我的目标是能够遍历数组并使用以下代码制作标记:

        <google-map
        :center="myCoordinates"
        :zoom="zoom"
        style="width:100vw; height: 100vh; max-width: 100%; margin: 0 auto;"
        ref="mapRef"
        @dragend="handleDrag"
    >
        <markermap
            :key="index"
            v-for="(m, index) in savedLocations"
            :position="{lat: m.position.lat, lng: m.position.lng}"
            :clickable="true"
            :draggable="false"
        />
    </google-map>

我将信息保存到数据库的格式如下:

     const post = {
        photo: this.img1,
        title: this.title,
        description: this.description,
        position: {
            lat: this.currentPlace.geometry.location.lat(), 
            lng: this.currentPlace.geometry.location.lng()
        },
        address: this.$refs.gmapAutocomplete.$refs.input.value
    }

    markerRef.push(post) // reference to database

此外,如果有更简单的方法可以做到这一点,那也将受到欢迎。 我的目标只是能够根据数据库中的信息在 map 上进行标记,并在单击它们时使用标题和图像展开它们。

感谢您的帮助。 干杯!

我的快速猜测是, this在您的代码中并不是您所期望的。 如果是这种情况,您可以使用=> (粗箭头)表示法来解决该问题:

ref.on("value", (snapshot) => {
    snapshot.forEach((childSnapshot) => {
        this.savedLocations.push(childSnapshot.val());
    })
}, (errorObject) => {
    console.log("The read failed: " + errorObject.code);
});

另请参阅: 如何在回调中访问正确的 `this`?

暂无
暂无

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

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