首页 > 解决方案 > Vue - 从 axios 响应中传递子组件的数据

问题描述

我有一个带有 2 个子组件的父组件。在 ChildComponent1 中,我使用 axios 获取我的数据并使用 v-for ( Cars to rent ) 列出它。每个数据块都有一个按钮,单击该按钮后,它应该选择该车辆。选定的车辆数据应传输到作为预订摘要卡或面板的 ChildComponent2。关联:

https://codesandbox.io/s/koyjjoo1y3

我不确定在这里采取什么方法。我使用道具将响应数据从父母传递给孩子。但我不知道如何在按钮单击时将数据从 1 个孩子传递给另一个孩子。

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 }}€&lt;/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>

标签: vuejs2

解决方案


您应该使用 $emit 引发事件,然后在其他组件中侦听该事件。


推荐阅读