Sharing Axios Response Data in VueJS: A Guide for Parent-Child Component Communication

Can someone please help me with using VueJS and Axios to retrieve API data and pass it to multiple child components? I am trying to avoid accessing the API multiple times in the child components by passing the data through props.

The issue I am facing is that the child component is currently returning 'undefined'.

Parent

<template>
    ...
    <my-child :foo="bar" />
    ...
    <my-other-child :foo="bar" />
    ...
</template>
<script>
    import axios from 'axios'
    ...
    mounted(){
        axios.get(...)
             .then(rsp => {this.bar = rsp.data.result})
             .catch(err => {console.warn(err)})
    }
    ...
</script>

Child

<script>
    props: ['foo'],
    mounted(){
        console.log(this.foo)
    }
</script>

Answer №1

If a condition is met, or not, it's easy to control what appears in the DOM with <code>v-if
and v-else. By using these directives along with a JavaScript expression, you can choose whether to include specific nodes, like your my-child components, in the DOM based on their truth value.

var application = new Vue({
  el: '#app',
  data: {
    bar: null
  },
  mounted () {
    setTimeout(() => this.bar = 'foo', 2500);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <div v-if="bar">bar is {{bar}}</div>
    <div v-else>bar is not initialized</div>
  </div>
</div>

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

Finding matches within a specific group in regular expressions

I am currently tackling the challenge of implementing a feature that involves detecting and linking phrases like "Co. Reg. No" in a specific HTML element. <div class="entry">The company with Co. Reg. No 1241515 will...</div> My goal is to cre ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...

How does VueJS compare to Angular Service functionality?

I am looking to consolidate all my server communication functions and data fetching utilities into a single reusable file within VueJS. Plugins don't seem like the ideal solution. Perhaps I should consider template-less components instead? ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

In my Vue watch method, I have two parameters specified, and one of them remains constant without any changes

Currently, I am attempting to access a method within my watch function with two parameters. Here is the code snippet for the method: onBoolianChange(value, willChange) { willChange = (value === false) ? true : false; }, watch: { "e ...

What is the method of updating content on a webpage without altering the page itself or using hashed URLs?

I have a good understanding of how to update webpage content through AJAX and loading remote content. However, I recently came across UStream's innovative new layout. When you click on any video, not only does the content change seamlessly without rel ...

Removing values when disabling a button using JavaScript

Within my code, I have two tables - one for non-clickable teams and another for clickable matches. Check out the image of the tables View the code on my GitHub repository let teams = [ {name: 'Roma', points: 0, wins: 0, draws: 0, loses: ...

Freezing Columns and Rows for a Spacious Scrollable Table

After extensive effort, I have been diligently striving to create a solution that allows a table's column headers to scroll with the body horizontally and the first column to scroll with the rows vertically. While I've come across solutions that ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Show the MySQL query results in a pop-up alert box

I need assistance with querying a MySQL database for certain results using PHP and then displaying the result in an alert dialog box through JavaScript. I am able to connect to the database, query the data successfully, and display it on a PHP page. Howeve ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

How to Condense an Element Using Position: Absolute

https://i.sstatic.net/GMUss.png I'm attempting to create functionality where the "Open Chat" button displays an Absolute positioned div, then hides it when clicked again. I experimented with using the react-collapse component, but encountered issues ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

A tutorial on adjusting camera angles through mouse dragging in Three.js

I have created a unique Rolex cube with varying layers along the "Z axis" and I need to adjust the camera position to preview the geometry accurately. How can I change the camera position by dragging the window and also manipulate individual cone rotations ...

Is it possible for a hybrid app using Angular 7/1.x to enable Hot Module Replacement (H

Having trouble implementing HMR on a hybrid Angular application using the downgradeModule strategy. I previously sought help from a similar question on Stack Overflow Can an Angular 5/1.x hybrid app support HMR? but didn't find a satisfactory answer. ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

Using Node's Express bodyParser() to access a JSON string that has been parsed

Question: How can I retrieve the parsed JSON object from the server side? I have successfully sent a JSON string to the server, but I am having trouble accessing the object once it is parsed. The client-side script for sending the JSON data is as follows ...

What causes compatibility issues between JEST and import statements in NEXTJS?

Just starting out with unit testing in JavaScript and I'm attempting to create a unit test for a Next JS project. However, when running the test, I encountered the following error: Code: import {isBase64} from '../../service/base64-service&a ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

Passing "this" to the context provider value in React

While experimenting with the useContext in a class component, I decided to create a basic React (Next.js) application. The app consists of a single button that invokes a function in the context to update the state and trigger a re-render of the home compon ...