vuejs2vue-componentvue.jsyandex-maps

How to initialize widget in component Vue?


I want to add maps in my app on VueJS.

As it descriped in manual I wrote in HEAD:

<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>

Then in App-component I did:

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view></router-view>
    <div id="map" style="width: 600px; height: 400px"></div>
  </div>
</template>

<script>
export default {
  name: 'app',
  created () {
    var map = new ymaps.Map("map", {
      center: [55.76, 37.64],
      zoom: 7
    });
  }
}
</script>

So in commandtool in chrome the following error:

ymaps.Map is not a constructor

So, how to initialize all what i want?


Solution

  • It's possible the api hasn't fully loaded when your map initialization code runs. You could try wrapping your initialization code in the ymaps.ready() function.

    export default {
      name: 'app',
      created() {
        ymaps.ready(() => {
          const map = new window.ymaps.Map("map", {
            center: [55.76, 37.64],
            zoom: 7
          }); 
        })
      }
    }
    

    I haven't tried this in a single-file component but was able to get it to work in a simple codepen example here.