【问题标题】:Loading external function from script to Vue component将外部函数从脚本加载到 Vue 组件
【发布时间】:2020-06-05 00:16:41
【问题描述】:

我正在尝试访问包含辅助函数的外部 js 脚本以在我的 Vue 组件中使用。我正在尝试使用https://www.geoplugin.com/webservices/javascripthttps://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
      });
  }

如果有任何帮助,我将不胜感激! :)

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    合并几个答案here,尝试将脚本添加到 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")
      }
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2017-03-29
      • 2021-09-04
      相关资源
      最近更新 更多