[英]Loading external function from script to Vue component
I'm trying to access external js -script containing a helper function to use in my Vue component.我正在尝试访问包含辅助函数的外部 js 脚本,以便在我的 Vue 组件中使用。 I'm trying to utilize https://www.geoplugin.com/webservices/javascript and https://www.npmjs.com/package/vue-plugin-load-script , inspired by this article: https://www.sitepoint.com/geo-location-2-lines-javascript/
我正在尝试利用https://www.geoplugin.com/webservices/javascript和https://www.npmjs.com/package/vue-plugin-load-script ,受本文启发: https://www .sitepoint.com/geo-location-2-lines-javascript/
I'm trying to access a city location of current user for my weather app, and if no result, use a predetermined city.我正在尝试为我的天气应用访问当前用户的城市位置,如果没有结果,请使用预定的城市。 The function I'm intrested in the external script file is
function geoplugin_city()
which returns a string of current city, for example "Sydney".我在外部脚本文件中感兴趣的函数是
function geoplugin_city()
,它返回当前城市的字符串,例如“悉尼”。
My block of code inside my Vue component is:我的 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
});
}
I would appreciate any help!我将不胜感激任何帮助! :)
:)
Amalgamating a few answers here , try adding the script to the dom and set its src property to your script's URL. 在这里合并一些答案,尝试将脚本添加到 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.