【问题标题】:Google Map not loading properly with vue js谷歌地图无法使用 vue js 正确加载
【发布时间】:2018-01-13 10:59:10
【问题描述】:

除非我按 ctrl+f5,否则 Google 地图不会加载属性。 我在 vue js 挂载的钩子中初始化地图。 显示的错误是

挂载钩子错误:“ReferenceError: google is not defined”

当我按 ctrl+f5 时一切正常

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

<script src="https://maps.googleapis.com/maps/api/js?key=****"
            async defer></script>
new Vue({
    el:'#app',
    mounted() {
         map = new google.maps.Map(document.getElementById('map'), {
             center: {lat: -34.397, lng: 150.644},
             zoom: 8
         });
    }
});

【问题讨论】:

  • 请提供您的组件代码。
  • 代码示例更新
  • TL;DR:您正在使用异步加载,这就是 GMaps 在安装钩子上不可用的原因。它仍在加载中。
  • 但在按 ctrl+f5 刷新页面时工作

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


【解决方案1】:

我建议为 Vue 使用现有的谷歌地图库,但如果你坚持按原样异步加载谷歌地图:

new Vue({
    el:'#app',
    created() {
         let script = document.createElement('script');
         script.src = 'https://maps.googleapis.com/maps/api/js?key=****';
         document.body.appendChild(script);
         script.load = function(){  
             map = new google.maps.Map(document.getElementById('map'), {
                 center: {lat: -34.397, lng: 150.644},
                 zoom: 8
             });
         };
    }
});

基本上,您必须侦听加载事件才能开始使用 API。

但我觉得在你的情况下,最好的做法是在你的 Vue.js 应用加载之前同步加载它,因为它可能完全依赖于 Google Maps API:

<html>
<body>
...
    <script src="https://maps.googleapis.com/maps/api/js?key=****"></script>
    <script src="path-to-your-app's-js"></script>
</body>
</html>

【讨论】:

  • 从 index.html 加载地图 API 的问题在于 Google 推荐的开发和生产密钥不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多