4

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?

2
  • Have you tried hitting the endpoint manually (i.e. curl) to make sure it's returning the correct data? Commented Nov 20, 2018 at 16:02
  • Could you try adding :key="$route.fullPath" to your <router-view> component. Commented Nov 20, 2018 at 17:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Apparently, changing to 'created' and moving that created method to the end of my component works for some reason. But now the issue is that when I bind that data in the component's template (or pass to a child component), I get an error cannot read property of undefined. Do I need to make the component async somehow? Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.