i want to learn to insert a external script like google maps into my vuejs component.
First of all, i have create the script tag and load in beforeMounted() to add to my page DOM.
beforeMount() {
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&callback=${CALLBACK_NAME}`;
script.onerror = rejectInitPromise;
document.querySelector('head').appendChild(script);
}
Second, create a function startLoading() which is called in my mounted() section.
methods() {
startLoding() {
const google = new google.maps.Geocoder();
console.log(google)
}
},
mounted() {
this.startLoding()
}
This code snippet above not work because “Uncaught ReferenceError: google is not defined”
If i store the new.google.maps.Geocoder() in a setTimeout it works
methods() {
startLoding() {
setTimeout(function() {
const google = new google.maps.Geocoder();
console.log(google)
}
}
},
mounted() {
this.startLoding()
}
So my question: how do i have to load the google script that my vue component can use the functions without an setTimeout?