Search code examples
javascriptvue.jsgetvuejs2xmlhttprequest

Fetch Data using Vue http based on Router params


I have searched around for an answer to this and also followed the example on the vue router documentation but am still having issues. I am trying to do an http call on initial load of a component and then also watch the router params and update the 'get' call from vue-resource.

My vue component js looks like this...

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

I have logged out the 'cityName' in my fetchData method and it always returns the right name, but when I append that 'cityName' to the http get call it is not returning the proper data. On initial load, this.city remains null and then each time I update the route, the data returns with the previous city selected instead of the new updated city in the route. I have tried Vue's created property in place of mounted and the same thing happens. Any ideas?


Solution

  • Try changing your fetchData method to the following:

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

    The => function notation keeps this in context of the component.