【问题标题】:Build axios url with vue data - getting undefined使用 vue 数据构建 axios url - 获取未定义
【发布时间】:2018-06-28 22:46:45
【问题描述】:

我正在尝试使用 axios 从 openweathermap 获取数据,目前,我正在通过使用一些方法从用户浏览器获取 lat 和 lon,然后调用构建 url 的函数来构建 url。

url 构建正确,没有任何问题,但是当我尝试使用 axios 调用 api 时,会发生奇怪的事情(基本上我得到了自己的页面 html 代码返回给我)

代码如下:

let weather = new Vue ({
  el: '#weather',
  data: {
    error: '',
    apiUrl: '',
    city: '',
    country: '',
    icon: '',
    description: '',
    results: [],
  },
  methods: {
    getPosition: function() {
      if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(this.getUrl);
      }else{
        this.error = 'Geolocation is not supported.';
      }
    },
    getUrl: function(position){
      let lat = position.coords.latitude;
      let lon = position.coords.longitude;
      this.apiUrl = buildWeatherUrl(lat, lon);
    },
    getWeather: function(){
      axios.get(this.apiUrl).then(function (response) {
        this.city = response.data.name;
        this.results = response.data;
      }).catch( error => { console.log(error); });
    }
  },
  beforeMount() {
    this.getPosition();
  },
  mounted() {
    this.getWeather();
  }
});

这是我第一次使用 Vue 和 axios,所以我不确定我在这里做错了什么。我还尝试在getWeather 函数中添加let self = this; 并将所有this 替换为self,但这不起作用。

问题是我正在尝试从 apiUrl 获取 URL,该 URL 应该由 getUrl 方法更新。虽然在安装后运行getWeather 时,url 似乎没有更新(如果它的硬编码它工作正常)。

感谢您的帮助。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    我怀疑问题出在navigator.geolocation.getCurrentPosition(this.getUrl); 这一行。

    this.getUrlnavigator回调时,函数不再有正确的this,因此this.apiUrl = buildWeatherUrl(lat, lon);将不起作用。尝试将this 绑定到this.getUrl,像这样

    getPosition: function() {
      if (navigator.geolocation){
        let getUrl = this.getUrl.bind(this)
        navigator.geolocation.getCurrentPosition(getUrl);
      }else{
        this.error = 'Geolocation is not supported.';
      }
    },
    

    或者干脆navigator.geolocation.getCurrentPosition(this.getUrl.bind(this));

    这个函数还有一个不正确的this

    axios.get(this.apiUrl).then(function (response) {
        this.city = response.data.name;
        this.results = response.data;
      }).catch( error => { console.log(error); });
    

    您要么需要重做之前的修复:

    我还尝试添加 let self = this;并将所有这些替换为 self in getWeather 函数,但它不起作用。

    或者干脆使用箭头函数。

    axios.get(this.apiUrl).then(response => {
        this.city = response.data.name;
        this.results = response.data;
      }).catch( error => { console.log(error); });
    

    这是关于如何管理 Javascript 的this 的最终堆栈溢出答案的链接:https://stackoverflow.com/a/20279485/2498782

    滚动到标有“常见问题:使用对象方法作为回调/事件处理程序”的答案部分。

    【讨论】:

    • 非常感谢 Eric 的帮助,不幸的是,axios 仍在 response.data 上返回我自己的 html 代码。我之前的 getPosition 函数也没有任何问题,但我已经添加了你的建议,看看是否可以解决它,不幸的是它没有
    【解决方案2】:

    我猜你在路由文件中将路由注册为POST 请求而不是GET 请求。只需将其更改为GET 即可修复代码。

    【讨论】:

    • 情况并非如此,因为我只是在处理一个调用 vue 实例的 js 文件
    • 你能console.log(this.apiUrl)并分享结果吗?
    • 在您的情况下,axios.get(this.apiUrl) 中的 url 不是合法的 url,或者正在返回某种垃圾值作为响应。
    • 我在那里使用我的 api 密钥,但基本上,它类似于:"http://api.openweathermap.org/data/2.5/weather?units=metric&lat=51.2514596563852&lon=-0.1661086240457241&APPID={{apikey}}
    • 我可能做了一些傻事,因为我试图注释掉所有的 Vue.创建了一个数据对象,构建了 url 并将其添加到数据对象中。当我控制台记录对象时,数据显示为空,但是当我从控制台打开它时,url 就在那里。我猜我的逻辑一定有问题
    【解决方案3】:

    我能够通过注释掉所有 vue 代码来解决这个问题,然后创建一个名为 data 的空对象并尝试将 api url 放入该对象中。在不断失败后,我意识到 url 无法从 navigator.geolocation.getCurrentPosition 中传递给对象,所以我使用了全局变量,有些东西打到了我,问题在于我如何尝试从 navigator.geolocation.getCurrentPosition 中获取 url /p>

    所以我通过在 vue 中的数据中添加 latlon 来解决这个问题,然后在调用 axios 之前构建 url。这给了我正确的结果。

    这是最终代码,以防它对某人有用。

        let weather = new Vue ({
      el: '#weather',
      data: {
        error: '',
        lat: 0,
        lon: 0,
        apiUrl: '',
        city: '',
        country: '',
        icon: '',
        description: '',
        results: [],
      },
      methods: {
        getPosition: function() {
          if (navigator.geolocation){
            var vm = this;
            navigator.geolocation.getCurrentPosition(this.updatePosition);
          }else{
            this.error = 'Geolocation is not supported.';
          }
        },
        updatePosition: function(position) {
            this.lat = position.coords.latitude;
            this.lon = position.coords.longitude;
        },
        getWeather: function(){
          let url = buildWeatherUrl(this.lat, this.lon);
    
          axios
          .get(url)
          .catch(function (error) {
            console.log(error);
          })
          .then(function (response) {
            console.log(response.data);
          });
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 2023-03-23
      • 1970-01-01
      • 2019-01-01
      • 2020-08-08
      • 2018-11-03
      • 2019-01-05
      • 1970-01-01
      • 2019-02-06
      相关资源
      最近更新 更多