Acquire information using Vue through HTTP requests based on Router parameters

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?

Answer №1

Consider updating your fetchData function with the code snippet below:

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

Using the => arrow function helps maintain the correct context of this within the component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance the visual appeal of mandatory input fields in virtuemart by incorporating star symbols

Is there a way to incorporate red stars into the form for mandatory input fields within Virtuemart 1.x? ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Having trouble getting jQuery to function properly in Safari

I am facing an issue with jQuery in the Safari browser. While my jQuery functions are functioning perfectly on GC, FF, IE, and Opera, they seem to fail when tested on Safari. My question is: Is there a specific code snippet that I can integrate into my w ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

How can I save or export an image file containing HTML content?

Currently, I am working on a project where I am generating dynamic HTML content. My goal is to be able to export or save this HTML content as an image file using PHP, jQuery, and JavaScript (or any other method if applicable). Can anyone help with the im ...

Exploring point clouds with three.js and NSF OpenTopography data: What's the best way to configure the camera and implement a controls library for seamless data navigation?

Currently, I am engaged in a small-scale project aimed at showcasing NSF OpenTopography data through a point cloud visualization using three.js. While I have successfully generated the point cloud, I am encountering significant challenges with setting up t ...

How can I keep dragging objects on Raphael JS Freetransform without showing the handles?

Hey there! Currently, I am immersed in a new project that hinges on the utilization of Raphael JS alongside the Raphael.Freetransform plugin. The plugin has been performing admirably with smooth transitions so far. Nonetheless, upon utilizing the hideHandl ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

"Limitation observed - function operates only on first attempt

I have been working on a map project that involves pulling information from Google about various locations using the library available at https://github.com/peledies/google-places In order to troubleshoot and identify the issue with the code related to ma ...

What could be causing the computed property to display as empty in the mounted hook, but functioning properly in all other instances?

In relation to the topic at hand, there is a specific item in my vuex store that I am accessing in my component through the computed properties section using mapState. The code for this process is as follows: computed: mapState({ orderTitle: state => ...

What could be preventing this AJAX call from running correctly?

I am in the process of developing a website that provides users with a discount based on a promotional code they can input. It is important for me to verify the validity of the code in our database before allowing a new sign-up to proceed. Below is the AJA ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

What is the best way to send variables from one page to another using jQuery or Javascript?

Is there a way to use POST with jQuery/Javascript to send data to another page and then redirect to that page? Instead of using GET... Using Javascript window.location = 'receivepage.php?variable='+testVariable; Once it's received by PHP ...

Manipulating values within a multidimensional array using JavaScript

I am attempting to populate a multidimensional array with data from a JSON file. The issue I am facing is that I am unable to update the content in the array: if(j>i && hoursYy == hoursY && secondsX == secondsXx){ wocheArray[i].count = wocheArray[i] ...

What is the best way to renew an access token with axios?

I have been struggling to understand the concept of refreshing tokens after reading numerous articles on the topic. They all seem too convoluted for me to grasp. Could someone please simplify it for me? Here is an overview of what I am trying to achieve: ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

Attempting to understand how to retrieve specific items from my MongoDB Database that are associated with a particular user based on their ID

I've been attempting to retrieve specific items (Portfolio pics) that have been submitted by a user from my Mongo Database. However, when I checked the extracted items using Console logs, it seems to display all portfolio pieces for every user instead ...

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...