简体   繁体   中英

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. 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/

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".

My block of code inside my Vue component is:

  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.

  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")
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM