Reputation: 393
So I'm confused to the best way to pass down data when building React or Vue apps.
Method 1) I had my child components calling functions that made API calls to get/refresh data on the component.
Method 2) I just recently made the switch, wherever possible, in these child components to put these API calls in the parent and the child component calls functions that call that one in the parent, and passes the new data in as props.
Are any of these the preferred way of handling data? Method 2 felt a little cleaner to me and it's not possible in all places but it felt like the parent should be responsible, when possible, to refresh the data, but that also makes the child dependent on the parent so I'm not sure anymore.
METHOD 1
<template>
<div>
<div v-for="(prod,index) in this.products" :key=index><
{{ prod.name }}
</div>
</div>
</template>
<script>
data() {
return {
products: []
}
},
mounted() {
this.getProducts();
},
methods: {
getProducts: function() {
axios.post('api/########', {
this.products: response.data,
})
}
</script>
METHOD 2
<template>
<div>
<div v-for="(prod,index) in products" :key=index><
{{ prod.name }}
</div>
</div>
</template>
<script>
props: {
products: {type: Array}
}
methods: {
getProducts: function() {
this.$parent.handleGetProducts()
*** PARENT WOULD HAVE FUNCTION HANDLEGETPRODUCTS TO MAKE THE API CALL AND PASS DOWN AND REFRESH THE PROPS GOING INTO THIS COMPONENTU**
}
</script>
Upvotes: 1
Views: 955
Reputation: 21030
When it comes to unidirectional data architecture on which both Vue.js and React are based, the following guidelines should be considered:
So what you are doing with method 2 is the long term solution keeping above guidelines in mind.
Upvotes: 5
Reputation: 5427
You can pass data in two ways in React.
For details you can check this article in medium Passing Data Between React Components
Upvotes: 0