Search code examples
vue.jsleafletvue-componentvuejs3

Vue.js 3 Mounting component instances at runtime


I'm trying out vue-leaflet/vue-leaflet and was trying to create many instances of <l-polyline> inside <l-map> component. But I don't know how to achieve that.

Static version (map comes with the polyline drawn):


<template>
  <l-map ref="map" v-model:zoom="zoom" :center="[47.41322, -1.219482]">
    <l-polyline
        :lat-lngs="[
        [47.334852, -1.509485],
        [47.342596, -1.328731],
        [47.241487, -1.190568],
        [47.234787, -1.358337],
      ]"
        color="green"
    />
  </l-map>
</template>

Dynamic attempt (prepare a function to add polylines programmatically, not working):

<template>
  <l-map ref="map" v-model:zoom="zoom" :center="[47.41322, -1.219482]">
  </l-map>
</template>

<script lang="ts">
function someAction(){
let poly= createApp(LPolyline,{
  latLngs:[[47.334852, -1.509485],
    [47.342596, -1.328731],
    [47.241487, -1.190568],
    [47.234787, -1.358337]]
});
poly.mount(this);

}

</script>

To clarify, I need a function to insert/append LPolyline components into the LMap component during runtime, it shouldn't be declared inside the LMap initially if possible.

I just started Vue.js so apologies if I'm making an obvious mistake. Thank you for your understanding.


Solution

  • Just add the components you want to use, and then feed them with data as any other Vue component. For example, you can load the polylines from an array with v-for:

        <l-map :zoom="zoom" :center="center">
          <l-polyline
            v-for="line in lines"
            :key="line.id"
            :lat-lngs="line.latLongs"
            :color="line.color"
          />
        </l-map>
    
    

    Have a look at the sandbox