初始化后在 Vue 中使用 Mapbox GL JS

Using Mapbox GL JS in Vue after initialization

我的Map.vue在下面,部分代码被简化了,所以我没有暴露任何信息。地图是我应用程序的一个组件,我想向它添加一些交互。但是,我的method不行,说read property 'getPitch' of undefined。我怎样才能初始化地图,以便以后仍然可以使用 Mapbox 的功能?

<template>
    <div id="map" class="map">
        <button @click="getPitch">Test</button>
    </div>

</template>

<script>
import mapboxgl from 'mapbox-gl';

export default {
    name: "Map",
    data() {
        return {
        };
    },
    props: {
        mapdata: {
            type: Object,
            default: () => { return {}; }
        }
    },
    beforeUpdate() {
            
        mapboxgl.accessToken = "...";

        const map = new mapboxgl.Map({
            container: "map",
            style: "...",
            center: ...,
            zoom: 11.85,
        });

        let mapRecords = this.mapdata.data;

        map.once('styledata', function() {

            map.addSource('...', {
            ...
            });

            map.addLayer({
            ...
            })
        });

    },
    methods: {
        getPitch() {
            map.getPitch();
        }
    }
};
</script>

<style scoped>
...
</style>

已解决

首先,将 beforeUpdate() 中的所有 map 个实例更改为 this.map。然后,在 getPitch 函数中,添加了这一行:let map = this.map;.

beforeUpdate 看起来不像是右勾拳。您可能应该使用 mounted.

此外,您的变量 map 超出了您的 getPitch 方法的范围。