I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the router parameters to update the 'get' call using vue-resource.
Below is my Vue component JS code...
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 checked the 'cityName' in my fetchData method and it consistently shows the correct name. However, when I include that 'cityName' in the http get call, it does not retrieve the expected data. On the initial load, this.city remains null, and every time I change the route, the data corresponds to the previous city selected rather than the newly updated city in the route. I attempted using Vue's created
property instead of mounted
, but encountered the same result. Any suggestions?