Vue.js method for creating components

Having recently started using Vue, I'm looking to implement an AJAX call each time my component is rendered. I have a Vue component named "test-table" and I want to retrieve the contents through an AJAX request. There are multiple tables like this, and I keep track of the active one using v-if/v-else-if conditions.

Currently, I have a workaround: in the component's template, I invoke a computed property named getData using
{{ getData }}
which triggers the Ajax call but only returns an empty string. I wish to switch to a proper solution but I'm unsure how to go about it.

Here is a snippet of my TypeScript code:

Vue.component("test-table", {
        props: ["request"],
        data () {
            return {
                tableData: [] as Array<TableClass>,
            }
        },
        template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
        computed: {
            getData() : string {
                get("./foo.php", this.request, true).then(
                    data => this.tableData = data.map(element => new TableClass(data))
                )
                return "";
            }
        }
}

HTML:

<test-table v-if="testcounter === 1" :request="stuff..."></test-table>
<test-table v-else-if="testcounter === 2" :request="other stuff..."></test-table>
...

The get method is asynchronous and sends a GET request to the server with request data. The last parameter specifies that the method should expect a JSON response, similar to jQuery's getJSON method.

The "created" hook does not work! It only runs once when the component is initially created. If I deactivate and reactivate it (using v-if), the method is not triggered again.

By the way, I'm using Vue 2.6.13

Answer №1

When a component is cached or used within a keep-alive, lifecycle hooks may not always fire consistently.

To troubleshoot this issue, try adding a console.log statement to each of the lifecycle hooks.

Consider switching to using a watcher instead, which can handle triggering the getData function again if the request changes.

  ...
  watch: {
    request: {
      handler: function() {
        this.getData()
      },
      deep: true
    }
  },
  created() {
     this.getData()
  },
  methods: {
    getData(): string {
      // execute request logic here
    }
  }

Answer №2

@FlorianBecker, have you considered using the lifecycle hook updated()? It could be more suitable for your current objective. For more information, you can check out the documentation here.

Answer №3

If your component is being rendered and unrendered using the v-if directive, you can utilize the mounted hook in this manner:

export default {
    mounted() {
        // perform ajax call here
        this.callAMethod();
    },
    ...
}

Another option is to use the created() hook, but keep in mind that it runs earlier in the lifecycle chain, meaning the DOM template may not be created yet and cannot be referenced. Typically, utilizing the mounted hook is the preferred approach.

For more detailed information on these hooks, visit this link.

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

Attempting to incorporate a variable into the URL while making an Ajax POST request using jQuery

Currently, I am attempting to create a post using jQuery.ajax instead of an html form. Below is the code I am using: $.ajax({ type: 'POST', // GET is also an option if preferred url: '/groups/dissolve/$org_ID', data: data, success: fu ...

What is the best way to map an array within an object stored in the Vuex state?

I have an array of objects in the items array. Each object contains another array called favs. I have successfully filtered the values of the objects, but now I need to filter or map the nested arrays within each object. Can anyone provide some guidance on ...

How can I use jQuery to implement a progress bar for Iframes loading?

My job involves working on an intranet where I have a complex aspx page with multiple Iframes, all of which we control. Each iframe is dynamically set using JavaScript/jQuery by different buttons on the page. Some buttons set the src attribute for iframes ...

Prevent Scrolling of Body Content within a Specified Div

In my current situation, I am dealing with a large number of divs (over 300) that are being used as part of an interactive background. The issue arises when viewing the page on mobile versus desktop – there are too many divs on desktop, causing excessive ...

Error: Attempting to import statement outside of module when calling JavaScript from Python (Dash)

I am attempting to incorporate a three.js example from the fireship-io YouTube channel to create an animated background on my Python dash application based on user scrolling. The JavaScript script continuously calls a function to update object rotation and ...

Update and modify content.php directly on the samepage.php rather than through externalpage.php by utilizing either Jquery or AJAX

Is there a preferred method for loading content on the same page instead of redirecting to an external page using AJAX or JQuery? Below is an excerpt from my external.php file: $id = null; if (!empty($_GET['id'])) { $id = $_REQUEST[ ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Material-UI exclusively incorporates specific components

Is there a way to include Material UI dialogs in my project without having to install the full Material UI library? I only need the dialogs component and don't want any other components included. Any suggestions or help on how to achieve this would be ...

Get binary information without relying on the use of arraybuffer

I have a specific resource that I am utilizing: function _arrayBufferToBase64(buffer) { var binary = ''; var bytes = new Uint8Array(buffer); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String. ...

What methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

Erase periods from the text box

Is there a way to remove the dots in the right bottom corner of a textarea without disabling resizing? https://i.sstatic.net/N2zfh.jpg I have seen a solution using the css property resize:none, but I would like to keep the resizing functionality... Are ...

The THREE.js WebGLRenderer canvas captures the 'click' mouse event

After including the domElement (canvas) from THREE.js WebGLRenderer in my document, I noticed that the 'click' mouse event no longer triggers when clicking on the container element containing the canvas. Is there a method to prevent the canvas f ...

What is the reason behind React deciding to skip the final question, even though it has been accurately saved to the

A simple web application was developed to calculate risk scores by asking five questions, with additional points awarded if a checkbox is checked. Despite extensive hours spent debugging, a persistent bug remains: the final question does not appear on the ...

Finding the distance between two points in JavaScript requires a simple formula

Here is a code snippet that generates two TRACER points and displays them on a map, as well as shows the union between the two points. <?php $latitudInicio = $_GET['latitudInicio']; $longitudInicio = $_GET['longitudInicio']; $latit ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

A potential issue of a race condition may arise with the cursor when utilizing Promise.all

Currently, in the project I am working on that utilizes nodejs and mongo, there is a particular function that accepts a query and returns a set of data based on the limit and offset parameters provided. Additionally, this function also includes a total cou ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

How can I dynamically update a React/Next.js page as the server completes different stages of a complex action?

Currently, my aim is to develop a single-page application that relies on one major back-end process. This procedure is initiated by a singular string input. The various stages involved and the outcomes are as follows: It takes about 20ms to display/render ...

Understanding the process of globally evaluating classes from files in node.js using the Eval function

Parent script with childscript integration const fs = require('fs'); function includeFile(f) { eval.apply(global,[fs.readFileSync(f).toString()]) } includeFile(__dirname+'/fileToRead.js'); hi(); ...

Mutual benefit in Parent and Child interaction

I am facing a situation where I have two components: Parent and Child. Here is the scenario: The Child component receives values from the Parent, which are constantly changing The Child component always reflects the updated value The Child component man ...