Using Vue 2.0 to Send Async Data to a Child Component

I have a main Vue component which sends data to its child through a prop. However, the data is not immediately available so the child component initializes with undefined values.

Is there a way to delay initialization until the data is ready?

Main Component:


var employeesData = new Vue({
  el: '#employees',
  data: { ... },
  methods: {
    fetchData: function(model, args=null) {

      let url = "/" + model + ".json"
      console.log(url);
      $.ajax({
        url: url,
        success: ((res) => {
          console.log(res)
          this[model] = res;
          this.isLoading = false;
        }),
        error: (() => {
          this.isLoading = false;
        }),
        complete: (() => {
          // $('.loading').hide();
          this.isLoading = false;
        })
      });

    },
    mounted: function() {
      this.fetchData(...)
      this.fetchData(...)
      this.fetchData('appointments')
    }
  }
})

The fetchData method gets called multiple times.

Answer №1

To conditionally render a component in the parent template, you can simply utilize the v-if directive:

<template v-if="readyToRender">
    <child-component :data="info"></child-component>
</template>

The child component will only be rendered when the variable readyToRender is set to true, so make sure to update this variable after all necessary processes are completed.

Answer №2

Utilize the Promise.all method.

In the provided snippet, a modification was made to the fetch function to return the promise from the ajax call. These promises can be collected in an array and passed to Promise.all to handle all ajax calls being completed before taking further action. For instance, by setting the isLoading property for utilizing v-if on a child component.

var employees = new Vue({
  el: '#employees',
  data: { isLoading: true },
  methods: {
    fetch(model, args=null) {
      let url = "/" + model + ".json"
      const success = res => this[model] = res
      const error = err => console.log(err)
      return $.ajax({url, success, error})
    }
  },
  mounted(){
    let promises = []
    promises.push(this.fetch('stuff'))
    promises.push(this.fetch('otherstuff'))
    promises.push(this.fetch('appointments'))
    Promise.all(promises)
      .then(() => this.isLoading = false)
      .catch(err => console.log(err))
  }
})

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

Struggling to properly line up the baselines of navigation list items that are styled as circular elements using CSS

I have transformed my navigation menu into a series of CSS circles with text inside. The issue I am facing is that the text spills out unevenly based on the amount of content in each circle. To address this, I used a JavaScript solution to center-align the ...

Assigning arbitrary hidden form data from dropdown selection

Would like to assign Layers Value as one of the following: GFS Meteogram 3day std or WRF 20 Global Meteogram 3day Std depending on the option selected from the dropdown menu <div><select id="myselect" class="productViewerParameter" name=" ...

Changing the caret position in a contenteditable div using HTML React

In a recent project I worked on, I included contenteditable divs. Whenever the enter key is pressed within one of these divs, it splits into two separate contenteditable divs. However, after React re-renders the components, the caret tends to go to the beg ...

Removing the empty option from Angular

I am encountering an issue with an empty option when cycling through an array. Below is the code snippet. View: <select ng-model="getseason" class="form-control"> <option ng-repeat="season in seasons" value="{{ season }}"> Seas ...

The input field is failing to update in response to changes in data inputted by the user

While developing my Vue.js application, I encountered a peculiar issue that has perplexed me. I am trying to manipulate an input field by implementing functionality such as increment and decrement buttons, as well as automatically erasing a zero value when ...

How to extract data from Google Sheets using NODEJS?

When utilizing the REST API to extract data from a cell range in Google Sheets, the response returned is as follows: { "range": "RECORD!A2:J2", "majorDimension": "ROWS", "values": [ [ "07/11/2016", "21:20:10", "3", "MAIN" ...

Tips for updating datatables following an ajax request

I've attempted various methods to refresh my data table following an AJAX Call but have had no success. I have tried using the draw() and ajax.reload() functions, but nothing seems to be working. Do you have any suggestions on how I can successfully r ...

How to update the selected autocomplete item in Vue using programming techniques?

Although I am still learning Vue, consider the following scenario: <v-autocomplete v-model="defaultUser" :hint="`User: ${defaultUser.username}`" :items="users" :item-text="item =>`${item.firstName} - $ ...

Reducing FLOUT in Vue Components: A Guide to Minimizing Markup Rendering

My challenge involves displaying a list of server-rendered items, each with a countdown timer. Initially, when the view component is nested within each dom element, there appears to be nothing on the screen. However, suddenly, POP, the view component exhib ...

Order of execution in Reading DB function

Currently, I am facing a challenge where I am trying to read data from a database and output the result as a string. The issue arises when the output turns out to be empty, leading me to believe that the "json" function is being executed before the datab ...

When is it appropriate to utilize this in JavaScript instead of an object literal?

After diving into the realm of OOP in JS, I found myself caught between traditional OOP and object literal approaches. Surprisingly, many impressive JS projects on Github were not following the typical 'OOP way'. Instead, they embraced patterns l ...

Discovering the Modification of a Variable Value in angularJS

Within my HTML markup, I have the following input field: <input id="Search" type="text" placeholder="Search Images.." ng-model="data" ng-keypress="($event.charCode==13)? searchMore() : return"> This input field serves as a search bar for us ...

CSS Horizontal Timeline Design

https://i.sstatic.net/zBXre.png Looking for an image like this one, with horizontal scrolling navigation buttons to dynamically update the list. I have included CSS and HTML code below. The task should be accomplished using only CSS, but JavaScript can be ...

Employing jQuery, how can one assign attributes to appended HTML and store them

So, I am currently working on a backend page for managing a blog. This page allows users to create, edit, and delete articles. When the user clicks the "edit" button for a specific article named 'foo', the following actions are performed: The ...

Implementing an onkeyup event for a custom form field in Drupal 6

Is there a way to implement an onkeyup event for a custom form field in Drupal 6? ...

Is there a way for me to programmatically modify a .env file using an npm script?

Currently, I'm managing a project with a .env file that contains confidential information. One of the key elements in this file is 'STATUS'. Just to clarify, this pertains to a Discord bot, The value assigned to the 'STATUS' var ...

Is it possible to integrate vanilla JavaScript (non-JQuery) into my Angular application?

As a newcomer to Angular, I've heard that it's best to forget about jQuery when developing an Angular application. Unlike designing a page first and then making it dynamic with jQuery, in Angular you build the app from scratch which can lead to c ...

Animating an element when another one fades away

const myVueInstance = new Vue({ el: '#app', data: { showBlueElement: true } }) .a, .b { height: 50px; width: 50px; background: red; } .b { background: blue; transition: transform 1s ease-in-out; } <script src="https://unpk ...

unleash the power of JavaScript to initiate a div opening

I would like to display a div when the mouse cursor hovers over a specific link, and then hide that div when the mouse cursor moves away from the link. ...

Incorporate Web-GL sandbox effects into an HTML webpage

I am searching for a method to showcase a Web-gl shader obtained from GLSL Sandbox on the background of an HTML page. Yet, it seems there is no simple embeddable API available. How can I accomplish this task? Can I integrate this specific Shader into an H ...