Executing a function within a VueJs 2 component immediately after it has finished loading

How can I retrieve data after a component has finished loading? When I initialize my Vue instance and load the component, the template loads correctly but the functions in the mounted lifecycle hook are not executed, causing the stats object to remain empty. This, in turn, leads to errors in the component or template that rely on the data.

So, how can I ensure that a specific function runs when the component is loaded?

It's worth mentioning that the functions I need to call will all make REST requests, but each component will be making different requests.

Vue.component('homepage', require('./components/Homepage.vue'), {
  props: ["stats"],
  mounted: function() {
    this.fetchEvents();
    console.log('afterwards');
  },
  data: {
    loading: true,
    stats: {}
  },
  methods: {
    fetchEvents: function() {
      this.$http.get('home/data').then(function(response) {
        this.stats = response.body;
        this.loading = false;
      }, function(error) {
        console.log(error);
      });
    }
  }
});

const vue = new Vue({
  el: '#main',
  mounted: function() {
    console.log('main mounted');
  }
});

Answer №1

Ensuring all initialization tasks are placed within the mounted lifecycle method is a solid approach. If your component is not refreshing, it could be due to how this is bound, as detailed below:

Within your fetchEvents function, the success handler from your $http call attempts to assign the response to this.stats. However, this assignment fails because this refers to the scope of the anonymous function rather than the Vue component.

To resolve this issue, consider utilizing arrow functions as illustrated below:

fetchEvents: function() {
  this.$http.get('home/data').then(response => {
    this.stats = response.body;
    this.loading = false;
  }, error => {
    console.log(error);
  });
}

Arrow functions preserve the context of this from their enclosing scope. By using this within the arrow function, you can ensure it still references the Vue component, allowing for proper data updates.

Note: It is recommended to also use arrow functions for error handlers to maintain access to the Vue component's this for error logging purposes.

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

Searching for values in JSON using jQuery's autocomplete feature

I have implemented jquery autocomplete with a json request in my code. Here is the code snippet for the autocomplete feature: $("#company_name").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ur ...

Generating dynamic page titles for Vue routes: A guide

I have a Vue-based website generated using Vue CLI, and I'm trying to find a way to dynamically generate page titles for views with dynamic routes. The website retrieves JSON data from a headless CMS, and I've set up dynamic routes for detailed v ...

What is the benefit of selecting the <body> element in a click event by utilizing .on() as opposed to .click()?

What are the advantages of using the second code over the first? Is it more efficient to directly select .vote a instead of selecting the body tag? I am in the process of developing a voting system that utilizes AJAX, JSON, and PHP: $('.vote a') ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Angular unburdened by jquery

I need help converting the following code from using JQuery to only Angular. I am unsure of how to accomplish this. Thank you! var startProduct = $("#product-overview").position().top - 60; var endProduct = $("#global-features").position().t ...

Mastering the art of looping through JSON values using AngularJS ng-repeat

Is there a way to use ng-repeat in order to iterate and access the name values: test01, test02, and test03 from my JSON data? Any guidance on how to achieve this using ng-repeat would be greatly appreciated. Thanks in advance! Check out this Fiddle link. ...

The checkbox will be automatically checked whenever there is any modification in the textbox

I'm currently working on a Grid view with a checkbox and two textboxes. What I want is for the checkbox to be automatically checked whenever there is a change in one of the textbox values, for example switching from 0 to 1. This project is being devel ...

`There is a problem of callbacks executing twice upon loading AJAX content`

My webpage is loading content using the waypoints infinite scroller plugin. After the AJAX call successfully adds DOM elements, a callback function is triggered to reinitialize javascript functionalities such as carousels, buttons, and other animations. ...

Tips for adjusting HTML files prior to HTMLOutput in Google Apps Script

I'm looking to make some changes to an HTML file within the doGet() function before it's output in HTMLOut. However, I'm running into an issue with the <?!=include('css').getContent();?> code snippet, as it can't be exec ...

The process of ensuring an element is ready for interaction in Selenium with Javascript

I am currently working on creating an automated test for a Single Page Application built with VueJs. When I click on the registration button, a form is loaded onto the page with various elements. However, since the elements are loaded dynamically, they are ...

Validating data for Telegram Web Bots using JavaScript

Struggling with creating a user verification script for my Telegram web app bots. Need help troubleshooting. import sha256 from 'js-sha256' const telegram = window.Telegram.WebApp const bot_token = '<bot-token>' const data_check_ ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Is there a way to eliminate duplicate pages from an EJS template pagination system?

I stumbled upon this helpful article that guides in implementing a pagination feature for my MEN stack app. The article provides a comprehensive overview from frontend to backend. While everything is working smoothly, I'm looking to make some adjustme ...

Guidelines on navigating a blank page using the Nuxt-js method

I have run into an issue in my Nuxt.js project where I need to open a link in a new target when a user clicks a button. Despite trying various solutions, I haven't been able to find a workaround within the Nuxt.js framework itself. <a :href=&qu ...

What is the reason for the request to accept */* when the browser is seeking a JavaScript file?

The html source appears as follows: <script type="text/javascript" language="JavaScript" src="myscript.js"></script> Upon debugging the http request using Fiddler, it is evident that the browser (Chrome) sends a GET request for myscript.js wi ...

What is the most effective method for implementing a fallback image in NextJS?

Lately, I've been immersed in a NextJS project that involves utilizing the YoutubeAPI to retrieve video details, such as thumbnail URLs. When it comes to fetching a full resolution image, the thumbnail URL typically follows this format: https://i.yti ...

JQuery Falters in Responding to Button's Click Action

Forgive me for what may seem like a silly question, but as someone new to JQuery, I have been struggling to figure out why my function is not displaying an alert when the button is clicked. Despite thorough research on Google, I haven't been able to f ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

update the markers on a leafletjs map

I am aiming to create a dynamic map with markers that update every 10 minutes. The marker positions are stored in a spreadsheet document that is regularly updated. After successfully retrieving the data from the spreadsheet and positioning the markers in ...