/ Gists / 06 Loading script inside the Vue.js
On gists

06 Loading script inside the Vue.js

cdruc vue

useScript.js Raw #

import {onUnmounted} from "vue";

export default function (src) {
  return new Promise((resolve, reject) => {
    let script = document.querySelector(`script[src="${src}"]`);

    if (!script) {
      script = document.createElement("script");
      script.src = src;
      script.async = true;
      script.setAttribute("data-status", "loading");
      document.head.append(script);
    }

    if (script.getAttribute("data-status") === "loaded") {
      resolve();
    }

    function onScriptLoad() {
      resolve();
      script.setAttribute("data-status", "loaded");
    }

    function onScriptError() {
      reject();
      script.setAttribute("data-status", "error");
    }

    script.addEventListener("load", onScriptLoad);
    script.addEventListener("error", onScriptError);

    onUnmounted(() => {
      if (document.head.contains(script)) {
        script.removeEventListener("load", onScriptLoad);
        script.removeEventListener("error", onScriptError);
        document.head.removeChild(script);
      }
    })
  });
}

AddressField.vue Raw #

<template>
  <div class="my-20 mx-auto px-10 w-full">
    <label class="block text-sm w-full font-medium text-gray-700">
      Street
      <input type="text"
             ref="streetRef"
             placeholder="Search street..."
             class="block mt-1 w-full text-sm placeholder-gray-400 rounded-md border-gray-300 focus:ring-blue-500 focus:border-blue-500">
    </label>
  </div>
</template>

<script>
import {onMounted, ref} from "vue";
import useScript from "../composables/useScript";

export default {
  setup() {
    const streetRef = ref(null);

    onMounted(async () => {
      await useScript("https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY&libraries=places");
      new google.maps.places.Autocomplete(streetRef.value);
    })

    return {
      streetRef
    }
  }
}
</script>