2017-08-10 106 views
0

我正在使用Google Maps API,並創建了一個組件來顯示地圖。在外部腳本加載後運行Vue組件的方法

的index.html:

<!DOCTYPE html> 
<html> 
<head> 
    ... 
</head> 
<body> 
<div id="app"></div> 
<!-- built files will be auto injected --> 
<script> 
window.show_google_map = false; 
console.log(window.show_google_map); 
function initMap() { 
    console.log('map loaded'); 
    window.show_google_map = true; 
    console.log(window.show_google_map); 
} 
</script> 
<script async defer 
     src="https://maps.googleapis.com/maps/api/js?key=googleapikeyxxxx&callback=initMap" 
     type="text/javascript"></script> 
</body> 
</html> 

GoogleMap.vue:

<template> 
    <div class="google_map" :id="map_name"></div> 
</template> 

<script> 
    export default { 
     name: 'google_map', 
     props: ['map_id'], 
     data() { 
      return { 
       map_name: this.map_id + '-map', 
      } 
     }, 
     methods: { 
      create_map() { 
       const element = document.getElementById(this.map_name); 
       const options = { 
        zoom: 14, 
        center: new google.maps.LatLng(51.501527, -0.1921837) 
       }; 
       const map = new google.maps.Map(element, options); 
       const position = new google.maps.LatLng(51.501527, -0.1921837); 
       const marker = new google.maps.Marker({ 
        position, 
        map 
       }); 
      } 
     }, 
     mounted() { 
      this.create_map(); 
     } 
    } 
</script> 

的問題是,在加載谷歌地圖API之前該組件呈現。如何在Google Maps API加載後顯示?

回答

0

如果我是你,我會在數據對象上創建一個名爲googleMapsReference的屬性並將它分配給window.google。然後用一個觀察者用typeof檢查它的值。如果它未定義,那麼你知道它沒有加載。如果你得到'對象',那麼你知道它有,你可以調用函數來創建地圖。

對不起,我會寫代碼,但我在我的手機上。

這裏的文檔:https://vuejs.org/v2/guide/computed.html

+0

是的,我想這樣的。但是,計算的屬性在加載時不會觸發。我更新了我的問題。請看一看。 – Kakar

+0

哦,我沒有提出一個計算屬性。而是一個觀察者。它與計算的屬性不同,它是雙向的。 –

+0

您無法觀看未定義的變量。 – Reiner

1

使用vue.mounted生命週期方法和加載gmaps腳本手動當組件被安裝在第一次。這樣,gmaps API被加載後,您可以kickstart的代碼(甚至工作以及對谷歌身份驗證API)

mounted: function() { 
    if (window.google && window.google.maps) { 
     this.create_map(); 
     return; 
    } 

    var self = this; 
    var script = document.createElement("script"); 
    script.onload = function() { 
     if (!window.google && !window.google.maps) 
      return void (console.error("no google maps script included")); 

     self.create_map(); 
    }; 

    script.async = true; 
    script.defer = true; 
    script.src = "https://maps.googleapis.com/maps/api/js?key=googleapikeyxxxx&callback=initMap"; 
    document.getElementsByTagName("head")[0].appendChild(script); 
}