Vue - Pass data from child component from axios reponse

vue fetch data from api
vue pass data to component
axios vue tutorial
vue api
vue props
vue watch

I have one parent component with 2 child components. In ChildComponent1 I use axios to get my data and list it with v-for ( Cars to rent ). Every block of data has an button which upon click, it should select that vehicle. The selected vehicles data should transfer to the ChildComponent2 which is a Booking summary card, or panel so to speak. Link:

https://codesandbox.io/s/koyjjoo1y3

I'm not sure what approach to take here. I used props to pass response data from parent to child. But I have no clue how can I pass that data from 1 child to another on button click.

Result.vue / Parent

    <section class="section__results--cars">

      <div class="col-lg-8">
         <cars-details></cars-details>
      </div>
      <div class="col-lg-4">
          <booking-summary></booking-summary>
      </div>
    </section>


CarsDetails.vue / Child1

<v-card class="mb-3" v-for="car in cars" :key="car.id">
  <img :src="car.image"></img>
     <h4 class="title">{{ car.title }}</h4>

        <car-attributes
           :maxPersons="car.maxPersons"
           :maxLuggage="car.maxLuggage"
           :interiorColor="car.interiorColor"
           :exteriorColor="car.exteriorColor"
        ></car-attributes>

        <div>
          <span class="price__title">Hourly price</span>
          <span class="price__value">{{ car.pricePerHour }}€</span>
          <v-btn @click="passData">Select Car</v-btn>
        </div>
        <div>
          <h6 class="subheading font-weight-medium">Description</h6>
          <p>{{ car.description }}</p>
        </div>
</v-card>
<script>
    import axios from "axios";
    const URL = "https://next.json-generator.com/api/json/get/NJgWweNm8";
    import CarAttributes from "@/components/cars/CarAttributes";
    export default {
      name: "carsdetails",
      components: { CarAttributes },
      data: () => ({
        cars: []
      }),
      mounted() {
        axios
          .get(URL)
          .then(response => {
            this.cars = response.data;
          })
          .catch(e => {
            this.errors.push(e);
          });
      }
    };
    </script>



BookingSummary.vue / Child2

<v-card>
   <h4>Booking Summary</h4>
   <h6>{{ car.title }}</h6>
   <h6>{{ car.maxPersons}}</h6>
</v-card>

The main design pattern is Data -> Down and Events <- Up. Use $emit('some-event', payload) to push the event up the chain, and use `@some-event="yourFunction" to handle it.

Here is an article that explains why this pattern works (and works long term): https://jasonformat.com/props-down-events-up/

For your use case

Parent

    <template>
      <div>
         <cars-details 
           v-for="(car, i) in cars" 
           :key="i" 
           :car="car" 
           @getCar="getCar" 
         />
      </div>
      <div v-if="selectedCar">
          <booking-summary :car="selectedCar" />
      </div>
    </template>

    <script>
      export default {
        data: {
          cars: [car1, car2, ...],
          selectedCar: null
        },
        methods: {
          getCar(car) {
            this.selectedCar = car
            // Do axios call for the `car` object
          }
        }
      }
    </script>


Child1

    <template>
      ...
      <div>
        ...
        <v-btn @click="passData">Select Car</v-btn>
      </div>
    </template>

    <script>
      export default {
        ...
        props: {
          car: { required: true }
        },
        methods: {
          passData() {
            this.$emit('getCar', this.car)
          }
        }
      }
    </script>


Child2

    <template>
      ...
    </template>

    <script>
      export default {
        ...
        props: {
          car: { required: true }
        },
      }
    </script>

Sending Data to Child Component after axios response, Hi, Basically I have two components . second component is load inside Sending Data to Child Component after axios response It is not enough to pass them in template, you have to define which ones will component use. Passing Data to Child Components with Props. Earlier, we mentioned creating a component for blog posts. The problem is, that component won’t be useful unless you can pass data to it, such as the title and content of the specific post we want to display. That’s where props come in. Props are custom attributes you can register on a component.

You should use $emit to raise an event, and then listen for that event in the other component.

React, How do you pass data from parent to child component in Reactjs? Answer (1 of 3): Chuoke ChungYoung since axios returns a promise object, return the axios.get() promise instead of passing the data to src variable, and then

You need to use vueJs eventBus to communicate with the components across the project. It is simple to use and declare.

// EventBus.js file

import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;

//CarsDetails.vue component (create event and pass data through it)

import EventBus from "../../EventBus";
export default {
  name: "carsdetails",
  data: () => ({
    isClicked: true,
    cars: []
  }),
  methods: {
    ok(car) {
      console.log(car);
      EventBus.$emit("finished", car);
    }
   }
};

//BookingSummary.vue component (listen to the event)

import EventBus from "../../EventBus";
export default {
  name: "bookingsummary",
  data() {
    return {
      car: null
    };
  },
  created() {
    EventBus.$on("finished", x => {
      this.car = x;
    });
    console.log(this.car);
  }
};

Here is the updated code https://codesandbox.io/s/n42j172jol

How to Pass Props Object from Child Component to Parent , { constructor(props){ super(props); } render() { return ( <div className="App"> <p>{this. props. Thanks I got it working now although not to happy about having to think of another condition going forward. There is also the fact that if you happen to use that myObject outside of the child component itself, let’s say a header html element in <root> now you end up having to addv-if also there, or even better right at the root element like so:

Vue.js REST API Consumption with Axios, How do you pass props from child to parent component? The line {{ BTCinUSD }} is a placeholder for the data that Vue.js will provide. This is how Vue lets us declaritively render data in the UI. Let’s define that data. Right below the <script> tag that includes Vue, add this code which will create a new Vue application and define a data structure which we’ll display on the page:

Fetching Data from a Third-party API with Vue.js and Axios, How do you call the parent component method from a child component in angular 6? When you want to pass data to a child component, you use props. Props are a simple way of passing dynamic reactive data between components. Passing Data. Say you have a parent component and a child component, and you want to pass the parent’s preciousThing data property down to the child. You can do so with a binding expression.

Parent-Child Component Communication ― Scotch.io, Fetching Data from a Third-party API with Vue.js and Axios First, we'll create a new Vue instance on the element div#app , and mock the response from We tell Vue what element to mount on, via the el option, and specify what Props: this is an array of data we want to pass down the component from  Using Query Parameters to Pass Data Between Routes. Query parameters in Vue.js work similar to router parameters with the exception that they are not required and the route doesn’t need to be altered before-hand. Head back into the project’s src/components/page1.vue file and alter the <template> block to look like the following:

Comments
  • You need eventBus to communicate between components.
  • Both answers are really good and helpful. I wonder what is the difference between your and his answer. As they both work, dealing with emitting events. I am new to this and try to understand. But thank you in any case. This was very helpful.
  • Also I added ` selectedCar: { title: "Choose a vehicle" }` - so that the Booking Summary tab doesn't throw an error, and is visible by default
  • Thank you very much, your and Grigios answers work well. I just had to accept one answer. but both work. I try to understand the difference between your answers. Much appreciated,
  • $emit works between parent child components only. Whereas eventBus is used to communicate across any 2 components (i.e they may or may not be parent child).
  • So eventBus could be used also to communicate between 2 seperate views? For example an input in 1 view could send the input data to the second view? Not talking about specifically related views?