Vue - Axios 응답에서 하위 구성 요소의 데이터를 전달합니다.
1개의 부모 컴포넌트와 2개의 자식 컴포넌트가 있습니다.Child Component 1에서 악시를 사용하여 데이터를 가져와 v-for(렌트할 자동차)에 나열합니다.모든 데이터 블록에는 클릭 시 해당 차량을 선택해야 하는 버튼이 있습니다.선택한 차량 데이터는 예약 요약 카드인 ChildComponent2 또는 패널로 전송되어야 합니다.링크:
https://codesandbox.io/s/koyjjoo1y3
여기서는 어떤 접근을 해야 할지 잘 모르겠어요.부모로부터 자녀에게 응답 데이터를 전달하기 위해 소품을 사용했습니다.하지만 어떻게 하면 한 아이에게서 다른 아이에게 버튼을 클릭해서 그 데이터를 전달할 수 있는지 모르겠다.
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>
주요 설계 패턴은 Data -> Down 및 Events <- Up 입니다.사용하다$emit('some-event', payload)
이벤트를 체인 위로 푸시하고 "@some-event="yourFunction"을 사용하여 이벤트를 처리합니다.
다음은 이 패턴이 작동하는 이유(및 장기적으로 작동하는 이유)를 설명하는 기사입니다.https://jasonformat.com/props-down-events-up/
사용 사례용
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>
$emit을 사용하여 이벤트를 생성하고 다른 컴포넌트에서 해당 이벤트를 청취해야 합니다.
프로젝트 전체에서 구성 요소와 통신하려면 vueJs eventBus를 사용해야 합니다.
사용 및 신고는 간단합니다.
// EventBus.js 파일
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;
//Cars Details.vue 컴포넌트(이벤트 생성 및 데이터 전달)
import EventBus from "../../EventBus";
export default {
name: "carsdetails",
data: () => ({
isClicked: true,
cars: []
}),
methods: {
ok(car) {
console.log(car);
EventBus.$emit("finished", car);
}
}
};
//Booking Summary.vue 컴포넌트(이벤트 리슨)
import EventBus from "../../EventBus";
export default {
name: "bookingsummary",
data() {
return {
car: null
};
},
created() {
EventBus.$on("finished", x => {
this.car = x;
});
console.log(this.car);
}
};
다음은 업데이트된 코드입니다.https://codesandbox.io/s/n42j172jol
언급URL : https://stackoverflow.com/questions/54370919/vue-pass-data-from-child-component-from-axios-reponse
'programing' 카테고리의 다른 글
VueJ에 컴포넌트를 재장착하는 방법 (0) | 2022.08.30 |
---|---|
Vue.js - v-for 내에서 필터 사용 (0) | 2022.08.30 |
오류: PostCSS 플러그인을 로드하지 못했습니다. 'postcss-import' 모듈을 찾을 수 없습니다(Vue 2). (0) | 2022.08.30 |
Java GUI 프레임워크뭘 고를까?Swing, SWT, AWT, SwingX, JGodies, JavaFX, Apache Pivot? (0) | 2022.08.30 |
나는 심판 vue 시험 utils를 사용하여 전자 요소를 선택할 수 있다. (0) | 2022.08.30 |