[英]Loading external function from script to Vue component
我正在嘗試訪問包含輔助函數的外部 js 腳本,以便在我的 Vue 組件中使用。 我正在嘗試利用https://www.geoplugin.com/webservices/javascript和https://www.npmjs.com/package/vue-plugin-load-script ,受本文啟發: https://www .sitepoint.com/geo-location-2-lines-javascript/
我正在嘗試為我的天氣應用訪問當前用戶的城市位置,如果沒有結果,請使用預定的城市。 我在外部腳本文件中感興趣的函數是function geoplugin_city()
,它返回當前城市的字符串,例如“悉尼”。
我的 Vue 組件中的代碼塊是:
mounted () {
// Access script
this.$loadScript("http://www.geoplugin.net/javascript.gp")
.then(() => {
// Do something with script
var city = geoplugin_city()
this.getWeather(city) // --> run my own weather function with city from script file
})
.catch(() => {
// Failed to fetch script
this.getWeather("Sydney") // --> run my own weather function with predetermined city
});
}
我將不勝感激任何幫助! :)
在這里合並一些答案,嘗試將腳本添加到 dom 並將其 src 屬性設置為腳本的 URL。
let script = document.createElement('script')
script.async = true
script.setAttribute('src', 'http://www.geoplugin.net/javascript.gp')
document.head.appendChild(script)
script.onload = () => {
let city = geoplugin_city()
this.getWeather(city)
}
script.onerror = error => {
this.getWeather("Sydney")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.