How to initialize widget in component Vue?

2019-07-12 21:13发布

问题:

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?

回答1:

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.



回答2:

I am not at all familiar with ymaps and don't seem to see it in npm, but here is the gist of what is going on here.

Think of each .vue file as a completely self contained file. It only has access to globally imported things from the Vue instance (i.e. this.$store from vuex is an example.

So to get a package in you must import it

<script>
import ymaps from 'whatever-this-package-is-named';

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

Then install it from npm, this will allow you to control version, bundle and distribute it.