簡體   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