Updating a Vue component upon resolution of a promise and effectively passing props to its nested children

I have a scenario where I need to pass data from a parent component to a child component as props. The parent component's data is fetched via an ajax call.

I have tried a couple of solutions, but they are not working as expected. Can you help me identify the error in my approach?

I also need to ensure that the props are correctly passed from the parent to the child component and its nested children.

Here are the attempts I have made:

  • When I do not use the 'v-if' directive, I receive an error stating that the :query is being passed as null.

  • Even after using v-if and updating the rendering, the child component remains empty and does not react to changes in the data.

  • I also tried to initialize the query data as computed without using the v-if directive, as it seemed like a simple caching solution.

  • Additionally, I attempted to emit an event using a bus, but the child component did not react to it.

  • Finally, I tried making the component reactive by using a :key attribute with a value like :key="ready", but it did not have any effect.

Template:

<template>
  <div v-if="isLoaded()">
      <input>
      <metroline></metroline>
      <grid :query="query"></grid>
  </div>
</template>

Script:

export default {

data() {
  return {
    ready : false,
    query : null
  }
},
components : {
  metroline : Metroline,
  grid : Grid
},
methods: {

    isLoaded() {
      return this.ready
    },

    firstQuery( uid, limit, offset) {

      var url = // my url
      
      // using Jquery to handle cross origin issues, solving with jsonp callback...
      
      return $.ajax({
        url : url,
        dataType: 'jsonp',
        jsonpCallback: 'callback',
        crossDomain: true 
        
        })

    }

},
created() {
  var vm = self;

  this.firstQuery(...)
      .then(function(data){
                 this.query = data;
                 console.log('firstQuery', this.query);

                 // attempts to pass through the query
                 // bus.$emit('add-query', this.query);

                 this.ready = true;
                 self.isLoaded(); // using a self variable, temporarily, jquery deferred messed up with this; however the this.query of vue instance is properly updated
                 
            })
}

}

Answer №1

When utilizing the created hook, make sure to assign the component instance this to a variable named that. This will allow you to access it within the callback, as the callback operates outside of the Vue component context (this):


created() {
  var vm = self;
  var that=this;
  this.firstQuery(...)
      .then(function(data){
                 that.query = data;
                 console.log('firstQuery', this.query);

                 that.ready = true;
                 self.isLoaded(); 
            })
}

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

Customize your file input with Bootstrap 4 using bs-custom-file-input and create a Symfony 5 collection with dynamic upload fields

The issue of not having a label for the chosen filename in a bootstrap 4 upload field has been resolved using the plugin https://github.com/Johann-S/bs-custom-file-input You can utilize "bs-custom-file-input" to showcase the selected filename in the boots ...

launch active link in pop-up dialog

I'm currently working on an Instagram iframe that fetches 9 random images with href links for pictures and spans with the same background. My goal is to display these images in a popup gallery. I've tried using Bootstrap for the popup, but I&apos ...

PHP Content File for Dynamic Ajax Website

I recently came across a very informative article that discussed how to create crawlable and link-friendly AJAX websites using pushState. The author provided detailed instructions on the process, but left out a crucial detail - how to store data in a PHP f ...

Leveraging Vue's `:is` property for dynamically rendering components using a configuration object

I have created a confirmation popup Vue component with the following configuration object: { title: null, message: null, onConfirm: null, onDismiss: null, modal_class: null, icon: null, confirmBtnText: null, confirmBtnColor: null, compon ...

Javascript postback functionality is fully operational in bootstrap 4, however, it is failing to return

Encountering an issue with my postback JavaScript function in the ASP/BootStrap environment. After searching on stackoverflow for a solution, I couldn't find one that resolved my problem. The problem is when I click on an image, the page reloads (the ...

Delete elements with identical values from array "a" and then delete the element at the same index in array "b" as the one removed from array "a"

Currently, I am facing an issue while plotting a temperature chart as I have two arrays: a, which consists of registered temperature values throughout the day. For example: a=[22.1, 23.4, 21.7,...]; and b, containing the corresponding timestamps for eac ...

The "truth" parameter within the xmlHttpRequest .open() function

After referencing MDN, it mentioned that by default, the JavaScript function will keep running until the server response is received. This is essentially what AJAX is all about - Asynchronous JavaScript and XML. Even though I have some experience with A ...

EJS.JS Error: Unable to find the title

I'm facing an issue with a script in express. I have a function that renders a view upon the success of another function. This project involves angular, node, express, and ejs as the view engine. However, when I try to render the view, I encounter an ...

Determine the position of the anchor/hash in the document

I am really struggling here. Whenever I try to enter index.html#about (or bookmark it and open it), I need to extract the index() of this and place it in the script below as "slideNumber". HTML Structure <div id="slideshow"> <div id="frontp ...

Despite receiving a 404 fetch response, the page still exists

I have encountered an issue with my Fetch code (POST) where the response shows status: 404 even though the URL returns a JSON when accessed through the browser. Surprisingly, changing the URL to https://httpbin.org/post brings back normal data. Furthermore ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Advanced jQuery Autocomplete with Nested Ajax Requests

I am currently developing a feature that allows users to search for albums using the Spotify Metadata API. The main functionality is working well, but I'm running into an issue with retrieving album cover art when making nested calls. This seems to be ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...

Having all elements at the same height

I am looking to enhance my JavaScript code to only impact 4 items at a time. The goal is to target the first 4 instances of .prodbox, adjust their height accordingly, then move on to the next set of 4 and repeat the process. This sequential adjustment will ...

Is there a way to display a foundation.css drop-down menu using jQuery?

After attempting to create a navigation bar using foundation.css, I encountered an issue where the sub-menu does not appear when hovering over it with the mouse. The main question at hand is how to display the sub-menu of test on this specific webpage. D ...

Can I use AJAX to load an entire PHP file?

My goal is to trigger a PHP file for sending an email when the countdown I created reaches zero. The PHP code contains the email message and does not involve any UI elements. I suspect that my approach may be incorrect, especially since I am not very fami ...

Obtain the accurate sequence of tr elements in the form of a jQuery object

Even though you can define tfoot before tbody in the source code, when displayed in the browser tfoot will still appear last: <table> <thead><tr><th>i get displayed first</th></tr></thead> <tfoot><t ...

Issue with div not updating after successful ajax request, troubleshoots fine on initial request but not subsequent ones

I have coded a livesearch feature in my header.php file. This livesearch functionality includes an 'Add to Cart' button for users to easily add products directly from the search results. Additionally, I have a Cart section in the header where the ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...