简体   繁体   English

MapBox:使用 Vue 的动态标记

[英]MapBox: Dynamic Markers with Vue

Can anyone advise which is the best way to call the marker1 & marker2 actions if the departure & arrival props are set?如果设置了departurearrival道具,任何人都可以建议调用marker1marker2动作的最佳方式吗? Is it to be done with async/await, if statement or for loop?是用 async/await、if 语句还是 for 循环来完成?

props: {
    departure: Object,
    arrival: Object
},
methods: {
    initMapBox() {
        const mapboxgl = require('mapbox-gl/dist/mapbox-gl.js');

        mapboxgl.accessToken = 'pk.eyJ1IjoiY3dHNkMDUifQ.xaSxrVMLZtfGAlWoGvB1PQ';
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/aasnapop/ck9d',
            center: [22.253, 45.419],
            zoom: 6
        });
        const marker1 = new mapboxgl.Marker({ color: '#FFFFFF', anchor: 'center' })
            .setLngLat([this.departure.longitude, this.departure.latitude])
            .addTo(map);

        const marker2 = new mapboxgl.Marker({ color: '#FFFFFF' })
            .setLngLat([this.arrival.longitude, this.arrival.latitude])
            .addTo(map);
    }

A Vue watcher allows you to listen to the component data and run whenever a particular property changes. Vue watcher 允许您监听组件数据并在特定属性更改时运行。

I recommend reading this as this does exactly what you want: https://v2.vuejs.org/v2/guide/computed.html .我建议阅读此内容,因为这正是您想要的: https ://v2.vuejs.org/v2/guide/computed.html。

Mounted definitely is an option however, my assumption from the async/await comment by the author was that they wanted to keep track of the props changing and not only when it gets added to the DOM. Mounted 绝对是一个选项,但是,我从作者的 async/await 评论中假设他们想要跟踪 props 的变化,而不仅仅是当它被添加到 DOM 时。 If they are only to be used once, then mounted is definitely the way to go.如果它们只使用一次,那么mounted绝对是要走的路。 @ehhc @ehhc

@DragonInTraining I'm not sure whether mounted wouldn't be the appropriate place for it. @DragonInTraining 我不确定mounted是否不适合它。 In that hook, the component is already fully created.在该挂钩中,组件已经完全创建。 So the props are set and can be used.这样道具就设置好了,可以使用了。 I don't think watchers would be good, because the props should not change later on..我不认为观察者会很好,因为道具以后不应该改变..

I suggest using the mounted -hook therefore: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram因此,我建议使用mountedhttps ://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

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

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