【问题标题】:Module Not Found error in Vue.js single page component using google maps使用谷歌地图的 Vue.js 单页组件中未找到模块错误
【发布时间】:2018-03-15 02:40:44
【问题描述】:

我正在尝试将 Google Maps API 从 Google Maps API 提取到我的 Vue.js 应用程序中。我已检索到生成的 API 密钥,并且正在尝试显示地图。当我运行该应用程序时,Atom 抛出一个未找到模块的错误消息,并且浏览器显示:Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\Project\client\src\components' 知道我做错了什么吗?

MyComponent.vue

<template>
  <div>    
  <div id="map">
  </div>
  </div>
</template>

<script>
  function initMap () {
    var options = {
      zoom: 8,
      center:{lat:39.9612,lng:-82.9988}
    }

    var map = new google.maps.Map(document.getElementById('map'), options);
  }
</script>

<script async defer type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap">
</script>

<style>
  #map{
    height: 400px;
    width: 100%;
  }
</style>

浏览器完全错误

./src/components/MyComponent.vue
Module not found: Error: Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\MyProject\client\src\components'
 @ ./src/components/MyComponent.vue 8:0-131 9:0-144
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 vue.js vuejs2


    【解决方案1】:

    您不能像这样将外部&lt;script&gt;s 添加到单个文件组件中。

    对于像您这样的案例,通常的方法是使用集成了 vue 和 google maps 的众多库之一。

    其中一些库提供了新的自定义元素供您使用:

    它们都有设置和实例化地图的简单细节。有关示例和用法,请参阅他们的页面。

    另一个采用更底层方法的方法是Js-GoogleMapsLoader。我并不是说这个比其他的更好——总的来说,从长远来看,vue 的具体细节可能会给你一个更容易的集成——但是由于它没有 Vue 的例子,所以你可以这样做使用它:

    • 运行npm install --save google-maps
    • MyComponent.vue 更改为:

      <template>
        <div>    
        <div id="map">
        </div>
        </div>
      </template>
      
      <script>
      import GoogleMapsLoader from 'google-maps'
      
      export default {
      
        mounted: function () {
          GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
          GoogleMapsLoader.load(function(google) {
            var options = {
              zoom: 8,
              center:{ lat: 39.9612, lng: -82.9988 }
            }
      
            var map = new google.maps.Map(document.getElementById('map'), options);
          });
        }
      }
      </script>
      
      <style>
        #map{
          height: 400px;
          width: 100%;
        }
      </style>
      

    以上选项都不需要额外的&lt;script&gt; 标签。

    【讨论】:

    • 干杯! Js-GoogleMapsLoader 选项有效。我会阅读这些内容。
    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2018-02-18
    • 2017-03-22
    • 2023-04-02
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多