2022-05-03
VUE3 做原生的 HTML5 表單驗證
JavaScript
2022.03.15
最近碰到一個問題是需要在 VUE 用 <script>
插入 JS 檔案,原本的做法是直接在 /public/index.html 插入即可,但有時候不是每一頁都會用到這個檔案,或是需要更有效地去控管他,所以可以改在 SFC 裡面插入這隻檔案。
以 google map api 為例,用 <script> 是這樣寫:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
然後我們可以改成以下寫法:
onMounted(() => { const key = '' const googleMapScript = document.createElement('script') const googleMapScript = document.createElement('script') googleMapScript.setAttribute( 'src', `https://maps.googleapis.com/maps/api/js?key=${key}&callback=initMap` ) googleMapScript.setAttribute('defer', '') googleMapScript.setAttribute('async', '') document.head.appendChild(googleMapScript) })
這樣就可以囉!