首页 > 解决方案 > 使用基于路由器参数的 Vue http 获取数据

问题描述

我已经四处寻找答案,并按照vue 路由器文档中的示例进行操作,但仍然遇到问题。我正在尝试对组件的初始加载进行 http 调用,然后还观察路由器参数并更新来自 vue-resource 的“get”调用。

我的vue组件js长这样...

export default {
  name: 'city',
  components: {
    Entry
  },
  data () {
    return {
      city: null
    }
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    '$route': 'fetchData'
  },
  methods: {
    fetchData() {
      const cityName = this.$route.params.name;
      this.$http.get('http://localhost:3000/cities?short=' + cityName).then(function(response){
        this.city = response.data;
      }, function(error){
        alert(error.statusText);
      });
      console.log(cityName)
    }
  }
}

我已经在我的 fetchData 方法中注销了“cityName”,它总是返回正确的名称,但是当我将该“cityName”附加到 http get 调用时,它没有返回正确的数据。在初始加载时,this.city 保持为空,然后每次我更新路线时,数据都会返回选择的前一个城市,而不是路线中新的更新城市。我已经尝试使用 Vue 的created属性来代替,mounted并且发生了同样的事情。有任何想法吗?

标签: javascriptvue.jsgetvuejs2xmlhttprequest

解决方案


尝试将您的fetchData方法更改为以下内容:

fetchData() {
  const cityName = this.$route.params.name;
  this.$http.get('http://localhost:3000/cities?short=' + cityName).then((response) => {
    this.city = response.data;
  }, (error) => {
    alert(error.statusText);
  });
  console.log(cityName)
}

=>函数符号保留this在组件的上下文中。


推荐阅读