Javascript 将外部函数从脚本加载到Vue组件
我正在尝试访问包含帮助函数的外部js脚本,以便在我的Vue组件中使用。受这篇文章的启发,我试图利用和: 我正在尝试为我的天气应用程序访问当前用户的城市位置,如果没有结果,请使用预先确定的城市。我在外部脚本文件中感兴趣的函数是Javascript 将外部函数从脚本加载到Vue组件,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我正在尝试访问包含帮助函数的外部js脚本,以便在我的Vue组件中使用。受这篇文章的启发,我试图利用和: 我正在尝试为我的天气应用程序访问当前用户的城市位置,如果没有结果,请使用预先确定的城市。我在外部脚本文件中感兴趣的函数是函数geoplugin\u city(),它返回当前城市的字符串,例如“Sydney” 我的Vue组件中的代码块是: mounted () { // Access script this.$loadScript("http://www.geoplugin.
函数geoplugin\u city()
,它返回当前城市的字符串,例如“Sydney”
我的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")
}