dev
dev

Reputation: 411

Leaflet objects as Vue components

TL;DR: I'd like to dynamically create and add objects (currently just polygons) to a Leaflet map using the Leaflet API, but make them reactive, letting Vue handle them and control some of their properties.

I'm trying to solve a seemingly very simple problem, but I think my brain isn't working properly because I can't think of a correct way to do it.

With Leaflet, I can call L.polygon(args).addTo(map), which returns a polygon object and inserts a path element into the DOM. However, these polygons will be created, modified and removed by the user, and some things should be made reactive (paths, styles, selection state, etc.), which makes me want to use Vue to simplify things.

I can see how I could achieve this by using either the Leaflet API or Vue, but not both. If I only use Leaflet, there's no reactivity. (I need external UI to respond to changes in the polygons and vice-versa.) If I only use Vue, I have to manually implement features Leaflet already takes care of (such as resizing the polygon when zooming). How can I take advantage of both?

Upvotes: 2

Views: 1208

Answers (1)

iH8
iH8

Reputation: 28638

This is in no means complete solution, but to big for a comment so i thought i'de throw it in here. Haven't worked with Vue, but in Angular, if you need to turn something in to a directive after angular has already run, you need to compile it. I had a look at the Vue API and they offer something similar called mount. It turns an element dynamicly added to the DOM into a component:

var polygon = new L.Polygon([...]).addTo(map);

Vue.component('polygon', {
    ready: function () {
        console.log(this.$el);
    }
});

var PolygonComponent = Vue.component('polygon');

new PolygonComponent().$mount(polygon._path);

Upvotes: 1

Related Questions