How to initialize widget in component Vue?

*爱你&永不变心* 提交于 2020-01-04 07:37:44

问题


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.



来源:https://stackoverflow.com/questions/42508390/how-to-initialize-widget-in-component-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!