Run The Method Of The Vue Component After The External Script Is Loaded
I am using google maps API, and have created a Component to display the map. index.html: ...
Solution 1:
Use the vue.mounted lifecycle method and load the gmaps script manually when the component is mounted for the first time. This way you can kickstart your code after the gmaps api was loaded (works even well for google auth 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)
returnvoid (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);
}
Solution 2:
If I were you, I'd create a property on the data object called googleMapsReference
and assign window.google
to it. Then use a watcher to check the value of it with typeof. If it's undefined then you know it hasn't loaded. If you get 'object' then you know it has and you can call the function to create map.
Sorry I'd write code but I'm on my phone.
Here's documentation: https://vuejs.org/v2/guide/computed.html
Post a Comment for "Run The Method Of The Vue Component After The External Script Is Loaded"