使用基于路由器参数的Vue http获取数据

时间:2018-11-20 15:51:26

标签: javascript vue.js get vuejs2 xmlhttprequest

我一直在寻找答案,也遵循vue router documentation上的示例,但是仍然有问题。我正在尝试在组件的初始加载上进行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保持为null,然后每次我更新路线时,数据都会返回并选择先前的城市,而不是路线中新的更新城市。我尝试使用Vue的created属性代替mounted,并且发生了同样的事情。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

尝试将您的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保留在组件上下文中。